簡體   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