C# 用反射覆盖属性
我想通过使用反射的自定义方法调用重写所有属性 唯一的方法是使用PropertyBuilder和ILGenerator?我刚刚找到了关于创建新程序集和新类的文档,但没有关于重写已定义类中的属性的文档 这是一个仅具有int属性的示例类C# 用反射覆盖属性,c#,reflection,C#,Reflection,我想通过使用反射的自定义方法调用重写所有属性 唯一的方法是使用PropertyBuilder和ILGenerator?我刚刚找到了关于创建新程序集和新类的文档,但没有关于重写已定义类中的属性的文档 这是一个仅具有int属性的示例类 public class Foo : MyContext { public int Bar { get; set; } public int Baz { get; set; } } public class MyContext { publi
public class Foo : MyContext
{
public int Bar { get; set; }
public int Baz { get; set; }
}
public class MyContext
{
public MyContext()
{
var props = this.GetType().GetProperties();
foreach(var p in props)
{
//...
}
}
protected void CustomSet(string propName, int value)
{
//...
}
protected int CustomGet(string propName)
{
//...
}
}
这是不可预期的行为
public class FooReflected : MyContext
{
public int Bar
{
get { return CustomGet("Bar"); }
set { CustomSet("Bar", value); }
}
public int Baz
{
get { return CustomGet("Baz"); }
set { CustomSet("Baz", value); }
}
}
唯一的方法是使用PropertyBuilder和ILGenerator引文,否则它不是真的。通常,您需要使用编译后步骤来完成此操作,就像使用Fody一样,这是一个用于在编译后修改已编译程序集的程序。例如,自动实现
INotifyPropertyChaged
:如果您不拥有该类的源代码,并且希望在运行时执行该操作-这里有一个重复:@Evk Wow。。。迷人的。。。我不知道。。。给“玩火”一个新的含义。。。更像是“玩凝固汽油弹”:-@xanatos这个问题的答案有点太多了: