C#泛型类,如何使用类型参数的派生类的公共属性?
我有两门C#的课:C#泛型类,如何使用类型参数的派生类的公共属性?,c#,visual-studio,generics,constraints,C#,Visual Studio,Generics,Constraints,我有两门C#的课: 公共抽象类BaseAccount { 公共无效MyMethod1() { //代码 } } 公共类DerivedAccount:BaseCount { 公共无效MyMethod2() { //代码 } } 公共类AccountBL,其中T:BaseAccount,new() { 公共void TestMethod() { T obj1=新的T(); obj1.MyMethod1(); obj1.MyMethod2();//错误!!!我可以在不更改常量的情况下在派生类中使用方法
公共抽象类BaseAccount
{
公共无效MyMethod1()
{
//代码
}
}
公共类DerivedAccount:BaseCount
{
公共无效MyMethod2()
{
//代码
}
}
公共类AccountBL,其中T:BaseAccount,new()
{
公共void TestMethod()
{
T obj1=新的T();
obj1.MyMethod1();
obj1.MyMethod2();//错误!!!我可以在不更改常量的情况下在派生类中使用方法吗??
}
}
如何在泛型类中使用派生类的公共属性
我不想为每个派生类实现几个泛型类。定义一个包含要访问的成员的接口,然后将类型参数限制为实现该接口的类型
public IMyInterface {
void MyMethod2();
}
public class AccountBL<T> where T : BaseAccounbt, new(), IMyInterface {
// Members can access T.MyMethod2()
}
公共IMyInterface{
void MyMethod2();
}
公共类AccountBL,其中T:baseAccount,new(),IMyInterface{
//成员可以访问T.MyMethod2()
}
与其他一些语言不同,C#只允许在符合类型参数要求的类型参数上引用成员。如果要使用
derivedcount.Method2()
,这一愿望已经是一个约束。显然,您需要T
才能成为您的客户
你可以这样做:
(obj1 as DerivedAccount)?.MyMethod2();
但我个人不喜欢混合类型转换和泛型。如果您的方法是泛型的,则意味着您不关心特定的运行时类型(除非它应该是
BaseAccount
)。然后添加类型检查似乎有点奇怪。这是因为您的结构。使用where T:BaseAccount,new()
您的意思是T必须继承自BaseAccount
,因此您可以使用BaseAccount
中的方法。如果要使用derivedcount
中的方法,必须首先检查以下内容:
if (obj1 is DerivedAccount ) {}
然后将其转换为deriveAccount
。因此,您可以得到以下结果:
public class AccountBL<T> where T : BaseAccount, new()
{
public void TestMethod()
{
T obj1 = new T();
obj1.MyMethod1();
if (obj1 is DerivedAccount )
{
(obj1 as DerivedAccount).MyMethod2();
}
}
}
公共类AccountBL,其中T:BaseAccount,new()
{
公共void TestMethod()
{
T obj1=新的T();
obj1.MyMethod1();
如果(obj1为衍生账户)
{
(obj1作为DerivedAccount).MyMethod2();
}
}
}
这里有一个可执行示例:这是因为您的结构。使用where
T:BaseAccount,new()
您的意思是T必须继承自BaseAccount
,因此您可以使用BaseAccount
中的方法。如果你想使用DerivedAccount
中的方法,你必须先检查一下。这可能很好,但有点难理解。我不确定,是否可以大规模?需要更多的思考。。。thanks@nimakhankhanizadeh你说的“大规模”是什么意思?
public class AccountBL<T> where T : BaseAccount, new()
{
public void TestMethod()
{
T obj1 = new T();
obj1.MyMethod1();
if (obj1 is DerivedAccount )
{
(obj1 as DerivedAccount).MyMethod2();
}
}
}