C# 泛型创建新实例

C# generics creating new instances

我正在尝试根据以下 myMethod:

编写一个 通用方法
void myMethod(myClassA instanceA, myClassB instanceB)
{
    instanceA = new myClassA(instanceB);
}

到目前为止我得到的是这样的(myMethod_new),其中有一些错误:

void myMethod_new<S, T>(S instanceA, T instanceB) where S : new()
{
    instanceA = new S(instanceB);
}

但是,由于我还没有掌握泛型在 C# 中的工作原理,因此应该如何实现?

如果类型在构造函数中有参数,则不能创建泛型类型的新实例。来自 docs(强调我的):

The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor.

一种选择是使用 Activator.CreateInstance 并传入所需的参数。但是,这可能会导致运行时异常,因为调用者可以使用任何格式的构造函数传入任何类型。

我的建议是通过删除构造函数参数并创建一个方法来传递该值,然后使用一个接口来约束它,从而稍微重构一下。例如:

// The interface
public interface IHasThing<T>
{
    void SetThing(T value);
}

// An implementation of the interface
public class Foo : IHasThing<string>
{
    private string _value;
    
    public void SetThing(string value)
    {
        _value = value;
    }
}

并且您更新的方法 returns 新对象:

public S myMethod_new<S, T>(T instanceB) where S : IHasThing<T>, new()
{
    var s = new S();
    s.SetThing(instanceB);
    return s;
}

所以现在你可以这样调用方法了:

var foo = myMethod_new<Foo, string>("bar");