Reputation: 3
namespace Test
{
public struct ABC
{
public const int x = 1;
public const int y = 10;
public const int z = 5;
}
}
namespace search
{
int A = 1;
how to search A in struct and get variable name 'x'
}
Upvotes: 0
Views: 140
Reputation: 101701
Using LINQ
and Reflection
, you can do the following:
var field = typeof (ABC)
.GetFields()
.FirstOrDefault(x =>x.FieldType == typeof(int) && (int)x.GetValue(null) == A);
if(field != null) Console.WriteLine(field.Name);
Upvotes: 0
Reputation: 432
static void Main(string[] args)
{
FieldInfo[] myFields = typeof(ABC).GetFields();
int A = 1;
foreach (FieldInfo field in myFields)
if ((int)field.GetRawConstantValue() == A)
Console.WriteLine(field.ToString());
Console.ReadKey();
}
public struct ABC
{
public const int x = 1;
public const int y = 10;
public const int z = 5;
}
I believe this would fit your needs, however I do think you should tell us what you're trying to do (your actual scenario), so we can better assist you.
Edit: don't forget to include System.Reflection
Upvotes: 0
Reputation: 73482
I think better option is to turn it to a enum.
public enum ABC
{
x = 1,
y = 10,
z = 5
}
Then you can use Enum.GetName.
string name = Enum.GetName(typeof(ABC), 1);//Will return x
Upvotes: 2