Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Общие вопросы по .NET и C# > Reflection и перегрузка свойств


Автор: Piphon 11.3.2008, 00:52
Доброе время суток.

Код

    class ParentClass
    {
        public virtual int Property1
        {
            get { return 0; }
            set { ;}
        }
    }

    class ChildClass1 : ParentClass
    {
        public override int Property1
        {
            get { return base.Property1; }
            set { base.Property1 = value; }
        }
    }

    class ChildClass2 : ParentClass
    {
        public new virtual int Property1
        {
            get { return 0; }
            set { ;}
        }
    }

    class ChildClass3 : ParentClass
    {
        public new virtual string Property1
        {
            get { return string.Empty; }
            set { ;}
        }
    }


Надо узнать с помощью Reflection:
  • ChildClass1.Property1 это перегруженное свойство ParentClass.Property1
  • ChildClass2.Property1 и ChildClass3.Property1  это новые свойства и не имеют не какой связи со свойством ParentClass.Property1


Автор: zaver 11.3.2008, 01:14
а что известно;)?

Автор: eskaflone 11.3.2008, 02:11
Код

class some
{
static void main()
{
    Type t = typeof(ChildClass1);
    PropertyInfo pi = t.GetProperty("Property1");

    Console.WriteLine(pi.Name + " " + pi.PropertyType);
}
}


Как понял твой вопрос так и ответил, пиши понятней что тебе надо.

Автор: Piphon 11.3.2008, 22:23
Цитата(zaver @  11.3.2008,  03:14 Найти цитируемый пост)
а что известно;)?

Известен только объект PropertyInfo.

eskaflone, лучше сформулировать не сумел :(

Код

        private static bool IsOverride(PropertyInfo prop)
        {
            MethodInfo method = prop.CanRead ? prop.GetGetMethod() : prop.GetSetMethod();
            MethodAttributes vtable  = method.Attributes & MethodAttributes.NewSlot;
            MethodAttributes virt = method.Attributes & MethodAttributes.Virtual;

            return  vtable != MethodAttributes.NewSlot && virt == MethodAttributes.Virtual;
        }


        static void Main(string[] args)
        {
            bool overClass1 = IsOverride(typeof(ChildClass1).GetProperty("Property1"));
            bool overClass2 = IsOverride(typeof(ChildClass2).GetProperty("Property1"));
            bool overClass3 = IsOverride(typeof(ChildClass3).GetProperty("Property1"));
        }

А это решение... Возвращает истину в том случае если свойство перегружено, и ложь если свойство новое.

Автор: eskaflone 12.3.2008, 00:59
а если так:
Код

class MyClass1
{
public virtual int Property1
        {
            get { return 0; }
            set { ;}
        }
}

class MyClass2 : MyClass1
{
}

class MyClass3 : MyClass2
{
public override int Property1
        {
            get { return 1; }
            set { ;}
        }
}

}


Твой метод правильно определит?

Мне кажется надо копать в сторону PropertyInfo.GetOptionalCustomModifiers 

Автор: Piphon 12.3.2008, 15:50
Возвращает истину.

Код для тестирования:
Код

    using System;
    using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {
            WriteInfo(typeof(MyClass3), "Property1");
            Console.ReadKey();
        }

        private static void WriteInfo(Type type, string name)
        {
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
            PropertyInfo prop = type.GetProperty(name, flags);
            if (prop == null) return;

            Console.WriteLine("Класс:          {0}", type);
            Console.WriteLine("Свойство:       {0}", prop);
            Console.WriteLine("Declaring Type: {0}", prop.DeclaringType);
            Console.WriteLine("Reflected Type: {0}", prop.ReflectedType);

            MethodInfo getter = prop.GetGetMethod(true);
            MethodInfo setter = prop.GetSetMethod(true);

            Console.WriteLine("Аттрибуты:      {0}", prop.Attributes);
            if (getter != null) 
                Console.WriteLine("Аттрибуты get:  {0}", getter.Attributes);
            if (setter != null) 
                Console.WriteLine("Аттрибуты set:  {0}", setter.Attributes);
            Console.WriteLine("Перегруженный:  {0}", IsOverride(prop));
            Console.WriteLine("Новый:          {0}", !IsOverride(prop));

            Console.WriteLine();
        }

        private static bool IsOverride(PropertyInfo prop)
        {
            MethodInfo method = prop.CanRead ? prop.GetGetMethod() : prop.GetSetMethod();
            MethodAttributes vtable  = method.Attributes & MethodAttributes.NewSlot;
            MethodAttributes virt = method.Attributes & MethodAttributes.Virtual;
            return  vtable != MethodAttributes.NewSlot && virt == MethodAttributes.Virtual;
        }
    }


Результат:
Код

    Класс:          MyClass3
    Свойство:       Int32 Property1
    Declaring Type: MyClass3
    Reflected Type: MyClass3
    Аттрибуты:      None
    Аттрибуты get:  PrivateScope, Public, Virtual, HideBySig, SpecialName
    Аттрибуты set:  PrivateScope, Public, Virtual, HideBySig, SpecialName
    Перегруженный:  True // что нам и надо было найти
    Новый:          False


Добавлено через 5 минут и 26 секунд
А на счет PropertyInfo.GetOptionalCustomModifiers() (а также PropertyInfo.GetRequiredCustomModifiers()), то здесь не все ясно. У меня они всегда возвращают пустой массив.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)