基于泛型的成员名
本文关键字:成员 泛型 于泛型 | 更新日期: 2023-09-27 17:51:23
是否有可能在c#中使用某种预处理器(或任何东西),就像在c++中一样,能够使用类型名称或泛型类型作为代码中的标识符?
public abstract class PropSC<T1, T2, T3>
{
public T1 T1 { get; set; }
public T2 T2 { get; set; }
public T3 T3 { get; set; }
}
所以我以后可以使用
public class SomeClass : PropSC<SomeBLL, OtherBLL, OtherClass> {...
作为书写
的快捷方式public SomeBLL SomeBLL { get; set; }
...
这在c#中是可能的吗?
不,使用泛型是不可能的。标识符需要在编译时知道,但泛型类型可以在运行时生成(例如使用MakeGenericType
)。
如果你真的需要这个,你必须使用某种代码生成工具。
虽然不可能完全按照您描述的那样做(没有反射器或其他纯粹的邪恶来源),但这会做一些类似于您所描述的事情:
public class Property<T1> {
T1 _t1;
T1 Get<T1>() {
return _t1;
}
void Set<T1>(T1 t1) {
_t1 = t1;
}
}
// C# doesn't have variadic generics, but you could do something like this
// to get multiple type arguments
public class Property<T1, T2> : Property<T1> {
T2 _t2;
T2 Get<T2>() {
return _t2;
}
void Set<T2>(T2 t2) {
_t2 = t2;
}
}
public class Property<T1, T2, T3> : Property<T1, T2> {
T3 _t3;
T3 Get<T3>() {
return _t3;
}
void Set<T3>(T3 t3) {
_t3 = t3;
}
}
public class Property<T1, T2, T3, T4> : Property<T1, T2, T3> {
// ...
不,后面的部分不是DRY,所以您可能希望最终将这种方法与一些反射合并。为了完整起见,下面是如何使用它:
public class SomeClass : Property<Thing1, Thing2, Thing3> { }
SomeClass someClass = new SomeClass();
someClass.Get<Thing1>();
someClass.Get<Thing2>();
someClass.Get<Thing3>();