简体   繁体   English

具有泛型构造函数的泛型类?

[英]Generic class with generic constructor?

I have a generic class. 我有一个通用类。 The constructor needs to accept an argument that is another instance of the same class. 构造函数需要接受一个参数,该参数是同一个类的另一个实例。 The problem is that the other instance can have a different generics type. 问题是另一个实例可能有不同的泛型类型。

Looks like C# allows me to have a method with it's own generics type, but this doesn't appear allowed for the constructor. 看起来C#允许我有一个带有它自己的泛型类型的方法,但这似乎不允许构造函数。

public class MyClass<T>
{
    public MyClass<T2>(MyClass<T2> parent = null)
    {
    }

    // ... Additional stuff
}

The code above tells me T2 is undefined. 上面的代码告诉我T2未定义。 It doesn't accept it as a method type. 它不接受它作为方法类型。

One approach would be to add a second generic type to my class. 一种方法是在我的班级中添加第二种通用​​类型。 But this is awkward and, in many cases, the argument will be null and there is not type. 但这很尴尬,在很多情况下,参数将为null并且没有类型。

Does anyone see a simple way around this? 有没有人看到这个简单的方法?

You are correct. 你是对的。 Generic constructors aren't supported. 不支持通用构造函数。

You could probably try the following: 您可以尝试以下方法:

Create a lower level common interface 创建一个较低级别的通用界面

public interface IMyClass {
    //...some common stuff
    IMyClass Parent { get; set; }
}

And use that as the common link between the types 并将其用作类型之间的通用链接

public class MyClass<T> : IMyClass {
    public MyClass(IMyClass parent = null) {
        Parent = parent;
    }
    public IMyClass Parent { get; set; }    
    // ... Additional stuff
}

Generic constructors aren't allowed. 不允许使用通用构造函数。 However, you can use a generic factory method instead. 但是,您可以使用通用工厂方法。

public class MyClass<T>
{
    public int Id { get; private set; }
    public int? ParentId { get; private set; }

    public static MyClass<T> Create(int id)
    {
        return Create<object>(id, null);
    }

    public static MyClass<T> Create<T2>(int id, MyClass<T2> parent = null)
    {
        var current = new MyClass<T>();
        current.Id = id;
        current.ParentId = parent?.Id;
        return current;
    }

    private MyClass()
    {
    }

    // ... Additional stuff
}

Sample use: 样品用途:

var intClass = MyClass<int>.Create(55);
var charClass = MyClass<char>.Create(234, intClass);
// charClass.ParentId is 55

This is only possible if you do not need to access any generic members of parent outside the factory method. 只有在您不需要访问工厂方法之外的任何parent通用成员时,才可以执行此操作。 If you do, you'd be better off abstracting it through a non-generic interface or base class. 如果这样做,最好通过非泛型接口或基类来抽象它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM