我有一个课程,例如:
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;
}
但是我不确定如何实现?
答案 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