繁体   English   中英

获取泛型类型的实例

[英]Get an instance of generic type

我有2个具有单独属性和验证方法的客户类BusinessCustomer和NormalCustomer。 在实现类中,根据某些条件,我可以创建Customer1或Customer2。 如何在Customer类中基于T创建BusinessCustomer或NormalCustomer的实例,以便可以调用这两个类共有的validate方法。

    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();
}

现在, BusinessCustomerNormalCustomer都需要实现上述接口:

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>实例,这将允许您调用CustomerTypeValidate方法。

接下来,如果要在构造函数中新建一个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();
}

需要返回一个布尔值(例如isValid ),或者签名需要为void Validate() 现在,您会遇到编译器错误,因为并非所有代码路径都返回一个值。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM