我在通用 DataGrid 中显示业务对象,我想通过自定义属性设置列标题,例如:
class TestBo
{
[Header("NoDisp")]
public int ID {get; set;}
[Header("Object's name")]
public String Name { get; set; }
}
到目前为止一切顺利,但我还想通过继承将显示与数据分开:
class TestBO
{
public int ID {get; set;}
public String Name { get; set; }
}
class TestPresentationBO : TestBO
{
//Question: how to simply set the Header attribute on the different properties?
}
我看到一个通过在 Child 构造函数中使用 SetCustomAttribute 进行反射的解决方案,但这会很麻烦,那么对于这个问题有一个简单而优雅的技巧吗?
请阻止我破坏数据/表示分离;o)
最佳答案
Question: how to simply set the Header attribute on the different properties?
无法按照您建议的方式在继承成员上设置属性,因为属性特定于类型。 SetCustomAttribute 不会帮助您 - 它只有在您在运行时 构造新类型时才有用。一旦属性被编译,您就不能在运行时更改它,因为它是元数据的一部分。
如果你想保持分离,你将不得不找到另一种方法。
(您可以使属性成为虚拟属性,在 Presentation 类中覆盖它们并在覆盖上添加属性,但这看起来很狡猾并且并没有真正分离任何东西 - 无论如何您最终会在 TestPresentationBO 中得到一个完整的 TestBO 类.. .)
关于C# 在继承类中为父属性添加自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2355294/