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'
}
-
6While this is likely possible with reflection, there's a pretty good chance that your object model is wrong if you even need to do this. Can you give a non-contrived example of what you're looking to accomplish?David– David2014-05-07 19:52:14 +00:00Commented May 7, 2014 at 19:52
-
Are you not allowed to change that struct? You'd probably be better off using array to loop through. Anywho, take a look at this: stackoverflow.com/questions/5873892/…sraboy– sraboy2014-05-07 20:00:40 +00:00Commented May 7, 2014 at 20:00
Add a comment
|
3 Answers
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
Comments
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
2 Comments
Selman Genç
if there is any field of different type that is not convertible to
int, this code will throw an InvalidCastExceptionRodrigo Silva
OP didn't mention anything to think otherwise.