Вопрос

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'
}
Это было полезно?

Решение 2

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);

Другие советы

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
        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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top