2011-05-25 89 views
3

看着this問題我開始考慮如何處理C#中的構造函數需求。泛型參數的構造器需求?

假設我有:

T SomeMethod<T>(string s) : where T : MyInterface 
{ 
    return new T(s); 
} 

我想設置它可以構造出一個串上T的要求,但據我所知,構造函數定義不允許作爲接口部分。有沒有一個標準的方法來解決這個問題?

回答

4

添加init方法或屬性的界面,

public interface MyInterface 
{ 
    void Init(string s); 
    string S { get; set; } 
} 

T SomeMethod<T>(string s) : where T : MyInterface, new() 
{ 
    var t = new T(); 
    t.Init(s); 

    var t = new T 
    { 
     S = s 
    }; 

    return t; 
} 

正如你不能指定參數構造函數約束

2

另一種方法是動態調用構造函數:

// Incomplete code: requires some error handling 
T SomeMethod<T>(string s) : where T : MyInterface 
{ 
    return (T)Activator.CreateInstance(typeof(T), s); 
} 

問題在於你失去了類型安全性:如果你嘗試在沒有匹配構造函數的MyInterface實現中使用它,它將不會打破例外。

1

如果你想有一個構造函數的字符串輸入它需要的,你需要實現一個抽象類:

public abstract class BaseClass<T> 
{ 
    public BaseClass<T>(string input) 
    { 
     DoSomething(input); 
    } 

    protected abstract void DoSomething(string input); 
} 

派生類則只需提供實現的抽象方法,它可以然後拿起它想要的任何接口。

public class Sample<T> : BaseClass<T>, IMyInterface 
{ 
    public Sample<T>(string input) 
     : base(input) 
    { 
    } 

    protected override void DoSomething(string input) 
    { 
    } 

    public void MyInterfaceMethod() 
    { 
    } 
} 
+0

我可以在'where T:BaseClass '中使用抽象基類嗎? – 2011-05-25 20:40:13

+1

這不會強制任何東西。派生類可以提供無參數的構造函數,只需將一個常量字符串傳遞給基類構造函數即可。 – 2011-05-25 23:09:05

+0

這是個好主意! – 2011-05-29 10:10:25