TypeDescriptor.Получите свойства (ThisType), чтобы возвращать свойства, доступные только для записи

StackOverflow https://stackoverflow.com/questions/772107

Вопрос

Я пытаюсь получить все свойства из типа, но с помощью TypeDescriptor.GetProperties(ThisType) предоставит мне только свойства, в которых есть как установщик, так и получатель.У меня есть свойства, доступные только для записи.Есть ли способ получить PropertyDescriptorCollection, включая эти?

/Асгер

Это было полезно?

Решение

Свойства, доступные только для записи, являются редким явлением и не существуют в системе.Пространство ComponentModel / PropertyDescriptor. PropertyDescriptors предназначены для того, чтобы быть удобочитаемыми.Я, вероятно, мог бы взломать HyperDescriptor чтобы вставить свойства только для записи, но это было бы взломом - и, по-видимому, пришлось бы создавать исключения для get, что может немного повлиять на вызывающий код.

В качестве отступления;Я вообще советую против свойства, доступные только для записи;пример из учебника, который люди просматривают, - это пароли (public string Password {private get;set;}) - Я бы гораздо предпочел иметь void SetPassword(string newPassword) способ...

Что вы на самом деле хотите сделать?Здесь есть целый ряд вариантов, и все они вполне достижимы:

  • используйте только отражение (медленно;может быть, это и не вариант)
  • использование Delegate.CreateDelegate (очень просто)
  • использование Expression.Compileмаленький сложнее, но не намного)
  • использование Reflection.Emit (довольно жестко)
  • свойства прокладки, доступные только для записи, в PropertyDescriptor (довольно жестко)

Если вы дадите мне знать, что вы на самом деле хотите сделать (а не то, как вы сейчас пытаетесь это сделать), я, возможно, смогу помочь больше.

В качестве примера с использованием Delegate.CreateDelegate (обратите внимание, что вы хотели бы где-нибудь спрятать делегат и повторно использовать его много раз):

отредактировано, чтобы показать, как это сделать, если вы не знаете конкретные типы во время выполнения

using System;
using System.Reflection;

class Foo
{
    public string Bar { private get; set; }
    public override string ToString()
    {
        return Bar; // to prove working
    }
}
static class Program
{
    static void Main()
    {
        ISetter setter = Setter.Create(typeof(Foo), "Bar");
        Foo foo = new Foo();
        setter.SetValue(foo, "abc");
        string s = foo.ToString(); // prove working
    }
}
public interface ISetter {
    void SetValue(object target, object value);
}
public static class Setter
{
    public static ISetter Create(Type type, string propertyName)
    {
        if (type == null) throw new ArgumentNullException("type");
        if (propertyName == null) throw new ArgumentNullException("propertyName");
        return Create(type.GetProperty(propertyName));
    }
    public static ISetter Create(PropertyInfo property)
    {
        if(property == null) throw new ArgumentNullException("property");
        if (!property.CanWrite) throw new InvalidOperationException("Property cannot be written");
        Type type = typeof(TypedSetter<,>).MakeGenericType(
                property.ReflectedType, property.PropertyType);
        return (ISetter) Activator.CreateInstance(
            type, property.GetSetMethod());
    }
}

public class TypedSetter<TTarget, TValue> : ISetter {
    private readonly Action<TTarget, TValue> setter;
    public TypedSetter(MethodInfo method) {
        setter = (Action<TTarget, TValue>)Delegate.CreateDelegate(
            typeof(Action<TTarget, TValue>), method);
    }
    void ISetter.SetValue(object target, object value) {
        setter((TTarget)target, (TValue)value);
    }
    public void SetValue(TTarget target, TValue value) {
        setter(target, value);
    }
}

Или, альтернативно, используя Expression API (.NET 3.5):

using System;
using System.Linq.Expressions;
using System.Reflection;

class Foo
{
    public string Bar { private get; set; }
    public override string ToString()
    {
        return Bar; // to prove working
    }
}
static class Program
{
    static void Main()
    {
        Action<object,object> setter = Setter.Create(typeof(Foo), "Bar");
        Foo foo = new Foo();
        setter(foo, "abc");
        string s = foo.ToString();
    }
}

public static class Setter
{
    public static Action<object,object> Create(Type type, string propertyName)
    {
        if (type == null) throw new ArgumentNullException("type");
        if (propertyName == null) throw new ArgumentNullException("propertyName");
        return Create(type.GetProperty(propertyName));
    }
    public static Action<object,object> Create(PropertyInfo property)
    {
        if(property == null) throw new ArgumentNullException("property");
        if (!property.CanWrite) throw new InvalidOperationException("Property cannot be written");

        var objParam = Expression.Parameter(typeof(object), "obj");
        var valueParam = Expression.Parameter(typeof(object), "value");
        var body = Expression.Call(
            Expression.Convert(objParam, property.ReflectedType),
            property.GetSetMethod(),
            Expression.Convert(valueParam, property.PropertyType));
        return Expression.Lambda<Action<object, object>>(
            body, objParam, valueParam).Compile();
    }
}

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

Использование System.Type.GetProperties() вместо этого это возвращает все свойства.Обратите внимание, что это возвращает PropertyInfo[] вместо того , чтобы PropertyDescriptorCollection.

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