获取泛型类型的实例
本文关键字:实例 泛型类型 获取 | 更新日期: 2023-09-27 18:18:59
我有两个客户类BusinessCustomer和NormalCustomer,它们有各自的属性和一个Validate Method。在实现类中,基于某些条件,我可能会创建Customer1或Customer2。如何基于Customer类中的T创建BusinessCustomer或NormalCustomer的实例,以便调用这两个类共同的验证方法?
public class Customer<T> where T : class
{
public T CustomerType;
bool isValid;
public Customer() //constructor
{
//for customer1, i want a new instance of BusinessCustomer
//for customer2, i want a new instance of NormalCustomer
}
public bool Validate()
{
isValid = CustomerType.Validate();
}
}
public class BusinessCustomer
{
public string CustomerHobby { get; set; }
public bool Validate()
{
return true;
}
}
public class NormalCustomer
{
public string CustomerEducation { get; set; }
public bool Validate()
{
return false;
}
}
public class Implement
{
public void ImplementCustomer()
{
var customer1 = new Customer<BusinessCustomer>();
customer1.CustomerType = new BusinessCustomer {CustomerHobby="Singing"};
customer1.Validate();
var customer2 = new Customer<NormalCustomer>();
customer2.CustomerType = new NormalCustomer { CustomerEducation = "High School" };
customer2.Validate();
}
}
您的第一个问题是以下行:
isValid = CustomerType.Validate();
由于CustomerType
是类型T
,它可以是任何类,编译器不能保证有Validate()
方法要调用。您需要通过创建一个公共接口来解决这个问题。我们称其为ICustomer
:
interface ICustomer
{
bool Validate();
}
现在,BusinessCustomer
和NormalCustomer
都需要实现上述接口:
public class BusinessCustomer : ICustomer
{
// Same code
}
public class NormalCustomer : ICustomer
{
// Same code
}
接下来,您必须更改:
public class Customer<T> where T : class
:
public class Customer<T> where T : ICustomer
现在,您只能在T
实现 ICustomer
的地方创建Customer<T>
实例,这将允许您调用CustomerType
的Validate
方法。
T
,您可以这样做:
public Customer()
{
CustomerType = new T();
}
但等待。如果T
没有默认的公共构造函数,或者是抽象的,该怎么办?我们还需要将约束添加到泛型类型:
public class Customer<T> where T : class, new()
现在,new T();
工作,你只能创建Customer<T>
的实例,其中T
有默认构造函数。如果你不想设置customer1.CustomerType
,你将不再需要设置。
另一个快速提示。你的方法:
public bool Validate()
{
isValid = CustomerType.Validate();
}
需要返回一个bool值(如isValid
),或者签名需要为void Validate()
。现在,您将得到一个编译器错误,因为不是所有的代码路径都返回值。
希望这对你有帮助!