【发布时间】:2013-03-03 14:58:02
【问题描述】:
是否可以将派生类的属性参数传递给其基类?
本质上,我正在尝试从派生类中设置属性的属性参数。
-
如何在 C++ 中完成
public class HasHistory<T, string name> { public HasHistory() { History=new History<T>(); } // here's my attribute [BsonElement(name)] public History<T> History { get; protected set; } }但是,非类型模板参数在 C++ 中是合法的,但在 C# 中是非法的。
-
C# 中的一个意想不到的解决方法
我意识到我可以将属性设为虚拟,并在派生类中添加属性。但是我会在构造函数中调用一个虚函数,虽然这可能有效,但这是不好的做法。
我确实想进行该调用,因为我希望基类构造函数初始化成员;这实际上是基类的重点。
public class HasHistory<T> { public HasHistory() { // this will be called before Derived is constructed // and so the vtbl will point to the property method // defined in this class. // We could probably get away with this, but it smells. History=new History<T>(); } // here's my property, without an Attribute public virtual History<T> History { protected set; get; } } public class Derived: HasHistory<SomeType> { // crap! I made this virtual and repeated the declaration // just so I could add an attribute! [BsonElement("SomeTypeHistory")] public virtual HasHistory<SomeType> History { protected set; get; } }所以我想我不能把属性放在基类中,而是把它放在派生类属性上,该属性使用/是根据受保护的基类属性实现的,但这太麻烦了,它消除了通过使用基类。
所以有一个好方法可以做到这一点,对吧?正确的?
如何重新定义继承自基的派生类的属性不覆盖派生类中的属性?
【问题讨论】:
-
不确定你对泛型中的
<T, string name>部分做了什么。 -
@ChrisSinclair 无效,但他试图说明他想要一个像 C++ 模板参数这样的 C# 机制。
-
您是否尝试在基类中应用该属性?据我所知,不可能将变量传递给属性,因为属性是在编译时而不是运行时处理的。
-
以上没有多大意义。类型变量实际上更类似于占位符,它们根据需要被请求的实际类型替换(当实例化泛型类的实例时)。例如,如果您要使用
string,那么您的属性将显示[BsonElement(string)],这对编译无效。 -
你希望用这个属性完成什么,也许还有另一种解决问题的方法?
标签: c# attributes base derived-class