How can you require a constructor with no paramete

2019-06-16 01:08发布

Is there a way?

I need all types that implement a specific interface to have a parameterless constructor, can it be done?

I am developing the base code for other developers in my company to use in a specific project.

There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).

The interface will be internal to the assembly

If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...

10条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-16 01:40

You do not need a parameterless constructor for the Activator to instantiate your class. You can have a parameterized constructor and pass all the parameters from the Activator. Check out MSDN on this.

查看更多
走好不送
3楼-- · 2019-06-16 01:42

No you can't do that. Maybe for your situation a factory interface would be helpful? Something like:

interface FooFactory {
    Foo createInstance();
}

For every implementation of Foo you create an instance of FooFactory that knows how to create it.

查看更多
来,给爷笑一个
4楼-- · 2019-06-16 01:43

You can use type parameter constraint

interface ITest<T> where T: new()
{
    //...
}

class Test: ITest<Test>
{
    //...
}
查看更多
我命由我不由天
5楼-- · 2019-06-16 01:46

I don't think so.

You also can't use an abstract class for this.

查看更多
登录 后发表回答