将属性传递给方法并在该方法内进行设置

时间:2019-06-04 14:27:58

标签: c# reflection

我有一个课程,例如:

public class MyClass
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public int SomethingElse { get; set; }
}

然后我想要一个method以便能够使用这样的参数调用它:

private void KeepingItDRY(MyClass myClass, string valueToSet, ????? PropertyNameToSetItOn)
{
    // some stuff 
    myClass.PropertyNameToSetItOn = valueToSet;
}

但是我不确定如何实现?

1 个答案:

答案 0 :(得分:2)

class Program
{
    static void Main(string[] args)
    {
        new Program().Run();
    }

    private void Run()
    {
        MyClass myClass = new MyClass();
        KeepingItDRY(myClass, "SomeName", "Name");
        System.Console.WriteLine(myClass.Name);
    }

    private void KeepingItDRY<T>(T target, object value, string property) =>
        typeof(T).GetProperty(property).SetValue(target, value);
}

public class MyClass
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public int SomethingElse { get; set; }
}

礼物:

SomeName