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

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

本文介绍了具有泛型构造函数的泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用类。构造函数需要接受一个参数,该参数是同一个类的另一个实例。问题是另一个实例可能有不同的泛型类型。

看起来像C#允许我使用它自己的泛型类型的方法,但是这不会出现允许构造函数。

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

// ...其他东西

$ / code>

上面的代码告诉我 T2 未定义。它不接受它作为方法类型。



一种方法是将第二个泛型添加到我的类中。但这很尴尬,在许多情况下,参数将是 null ,并且没有类型。



任何人都可以看到一个简单的解决方法吗? 解决方案

你是对的。不支持通用构造函数。



您可以尝试以下操作:

创建一个较低级别的通用接口

  public interface IMyClass {
//...some常用的东西
IMyClass父类{get;组; }
}

并将其用作各种类型之间的常用链接

  public class MyClass< T> :IMyClass {
public MyClass(IMyClass parent = null){
Parent = parent;
}
public IMyClass Parent {get;组; }
// ...其他东西
}


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.

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

    // ... Additional stuff
}

The code above tells me T2 is undefined. 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.

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
}

这篇关于具有泛型构造函数的泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:53