4

何らかの理由で、PropertyInfoいくつかのクラスのプロパティに対応するインスタンスの Dictionary を作成する必要があります (それを と呼びましょうEntityClass)。

わかりました、使用できますtypeof(EntityClass).GetProperties()

しかし、いくつかの特定のプロパティ (コンパイル時に既知) の値を決定する必要もあります。通常、次のいずれかを実行できます。

EntityInstance.PropertyX = Value;
typeof(EntityClass).GetProperty("PropertyX").SetValue(EntityInstance, Value, null);

ディクショナリを埋めるにはPropertyInfo、通常どおり値を設定するだけでなく、インスタンスを使用する必要があります。しかし、文字列名でプロパティを取得するのは快適ではありません。一部の EntityClass が変更されると、コンパイル エラーではなく多くの例外が発生します。だから、私が尋ねるのは:

文字列名を渡さずに既知のプロパティの PropertyInfo を取得する方法は? デリゲートのようなものがあるといいのですが:

SomeDelegateType MyDelegate = EntityInstance.MethodX;

理想的には:

SomePropertyDelegate MyPropertyDelegate = EntityInstance.PropertyX;
4

2 に答える 2

4

何が必要かはわかりませんが、先に進むのに役立つかもしれません。

public class Property<TObj, TProp>
{
    private readonly TObj _instance;
    private readonly PropertyInfo _propInf;

    public Property(TObj o, Expression<Func<TObj, TProp>> expression)
    {
        _propInf = ((PropertyInfo)((MemberExpression)expression.Body).Member);
        _instance = o;
    }

    public TProp Value
    {
        get
        {
            return (TProp)_propInf.GetValue(_instance);
        }
        set
        {
            _propInf.SetValue(_instance, value);
        }
    }
}

public class User
{
    public string Name { get; set; }
}

var user = new User();
var name = new Property<User, string>(user, u => u.Name);
name.Value = "Mehmet";
Console.WriteLine(name.Value == user.Name); // Prints True
于 2013-05-27T16:56:21.143 に答える