Designer requirements for generics?

Considering this question, I started thinking about how to handle constructor requirements in C #.

Suppose I:

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

I want to set the requirement to Tso that it can be built from a string, but as far as I know, constructor definitions are not allowed as part of the interfaces. Is there a standard way to solve this problem?

+3
source share
3 answers

Add an initialization method or property to your interface,

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;
}

How you cannot specify arguments for constructor constraints

+4
source

Another way is to dynamically call the constructor:

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

, : MyInterface, , .

+2

If you want to have a constructor that accepts string input, you need to implement an abstract class:

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

     protected abstract void DoSomething(string input);
}

Then your derived class simply provides an abstract method implementation, and it can then get any interfaces it needs.

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

    protected override void DoSomething(string input)
    {
    }

    public void MyInterfaceMethod()
    {
    }
}
+1
source

All Articles