c# - 作为通用值的结构数组

标签 c# generics

我正在尝试使用结构数组作为通用参数,如下所示:

new Test<S[,]>()

这很简单,除了我的类需要创建一个 T 的实例,如下所示:

T s = new T();

这给我带来了各种编译时错误。我尝试了几种解决这些错误的方法,但没有成功。

下面是一些示例代码来说明错误和我尝试过的方法:

class Program
{
    static void Main(string[] args)
    {
        var t1 = new Test<S[,]>();

        // ERROR: 'Program.S[*,*]' must be a non-abstract type
        // with a public parameterless constructor in order to
        // use it as parameter 'T' in the generic type or method
        // 'Program.Test2<T>'
        var t2 = new Test2<S[,]>();

        // ERROR: 'Program.S[*,*]' must be a non-nullable value
        // type in order to use it as parameter 'T' in the generic
        // type or method 'Program.Test3<T>'
        var t3 = new Test3<S[,]>();

        // ERROR: 'Program.S[*,*]' must be a non-nullable value
        // type in order to use it as parameter 'T' in the generic
        // type or method 'Program.Test3<T>'
        var t4 = new Test4<S[,]>();
    }

    struct S
    {
    }

    class Test<T>
    {
        // ERROR: Cannot create an instance of the variable type 'T'
        // because it does not have the new() constraint
        T s = new T();
    }

    class Test2<T> where T: new()
    {
        T s = new T();
    }

    class Test3<T> where T: struct
    {
        T s = new T();
    }

    // ERROR: The 'new()' constraint cannot be used with the 'struct' constraint
    class Test4<T> where T : struct, new()
    {
        T s = new T();
    }
}

是否有解决此问题的简单方法?

最佳答案

你的错误给了你答案。 new() 约束不能用于结构(new() 和struct 约束不能一起使用)。 因此,除非必须将 S 作为结构,否则我会将 S 更改为类并解决问题。但是您必须将 S 作为结构,然后我建议的解决方法是创建一个包装类。

public class Wraper
{
    Wrapper(){}
    Wrapper(S value){
        this.Value = value;
    }

    public S Value {get; set;}

    public static implicit operator S(Wrapper wrapper){
        return wrapper. Value;
    }

    public static implicit operator Wraper(S s){
        return new Wrapper(S);
    }
}

现在你可以定义你的测试如下:

class Test<T> where T : Wrapper, new()
{
    T value;

    //as you have provided implicit conversion from S to Wrapper and vice versa
    //something like this should work
    public S Value{
        get{ 
            //implicit conversion from Wrapper to S;
            return this.Value;
        }

        set{
            //implicit conversion from S to Wrapper
            this.value = value;
        }
    }
}

关于c# - 作为通用值的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37359138/

相关文章:

c# - 什么是 ServiceObjectiveId?

c# - 该列在选择列表中无效,因为该列未包含在聚合函数或GROUP BY子句中

c# - 在 UserControl C# .NET 中添加/停靠控件

java - 在运行时转换之前检查通用类型

java - 获取通用基础存储库的参数类型名称

generics - 如何为泛型 Vec<T> 的向量实现特征?

c# - 在 Entity Framework 6 中使用规范化数据?

c# - 从 TaskScheduler 中取消 TPL 任务

java - 整数哈希集

c# - 将通用集合转换为C#2.0中的具体实现