开发者

Using an interface for a generic type with parameterless constructor constraint?

I have a generic class, say MyCollection<T>, that needs its generic type T have a parameterless constructor. I have an interface IMyInterface with all implementetations 开发者_开发问答having parameterless contructors, but I cannot tell that fact to the compiler, so I cannot use IMyInterface as the type parameter T. What should I do?

public class MyCollection<T> where T : new()
{
    bla bla ...
    T t = new T();
}

public interface IMyInterface
{
    bla bla ...
}
...
MyCollection<IMyInterface> x;   //Compile Time Error

I know that almost the same question was asked in Interface defining a constructor signature? but it is two years old and I'm hoping maybe someone can suggest a workaround in C# 4.0.


This won't work because T t = new T(); with the interface as T, it would become IMyInterface t = new IMyInterface(); which is completely invalid. You have to know what the concrete implementation to construct your type. You cannot use an abstract type or interface alone with new. If MyCollection is your own class if you added a parameter in the constructor to set T t in the constructor by passing in your concrete implementation and remove the new parameter constraint and use the interface as a generic parameter then.


Another way to deal with generic classes that have to be able to construct things of the generic type but which cannot for whatever reason use the New constraint is to either pass a factory to the methods that will have to create new objects of the generic type, or require as part of the interface that classes implementing it provide a means of creating another instance. For example of the first usage, one might define an interface IFactoryFromString<T> which includes a method "T CreateFromString(String st)", and pass such a factory to a routine which needs to be able to create a T given a string. For example, For example of the second usage, an interface for something that behaves as tree node might include a method to create another similar tree node. The second usage avoids the need for additional factory classes and parameters, but requires that one actually have an instance of a class meeting a constraint in order to produce another one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜