2011-05-25 63 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