加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C#中使用带有模板的new运算符

发布时间:2020-12-16 01:54:56 所属栏目:百科 来源:网络整理
导读:我想弄清楚如何在C#中使用模板.我写了这个: public static ListTValue deepCopyListTValue(ListTValue src){ ListTValue arr = new ListTValue(); for (int i = 0; i src.Count; i++) { arr.Add(new TValue(src[i])); //Error on this line } return arr;}
我想弄清楚如何在C#中使用模板.我写了这个:

public static List<TValue> deepCopyList<TValue>(List<TValue> src)
{
    List<TValue> arr = new List<TValue>();

    for (int i = 0; i < src.Count; i++)
    {
        arr.Add(new TValue(src[i]));   //Error on this line
    }

    return arr;
}

但是我收到一个错误:

error CS0304: Cannot create an instance of the variable type ‘TValue’
because it does not have the new() constraint

解决方法

#1:接口的新约束

向TValue添加一个约束,告诉编译器它有一个无参数构造函数.您可以通过在TValue的约束中添加关键字new来实现此目的.这样你至少可以构建一个项目.

您不能使用通用参数类型的参数.但您可以使用另一个约束来定义一些属性:

public interface IMyValue<TValue>
{
    void CopyFrom(TValue original);
}

public static List<TValue> deepCopyList<TValue>(List<TValue> src)
    where TValue: IMyValue<TValue>,new() // <== Setting the constraints of TValue.
{
    List<TValue> arr = new List<TValue>();

    for (int i = 0; i < src.Count; i++)
    {
        TValue value = new TValue();
        value.CopyFrom(src[i]);
        arr.Add(value); // No error.
    }

    return arr;
}

#2:使用ICloneable

还有第二种解决方案,它有点相同.使用ICloneable使值自行关闭它:

public static List<TValue> deepCopyList<TValue>(List<TValue> src)
    where TValue: ICloneable // <== Setting the constraints of TValue.
{
    List<TValue> arr = new List<TValue>();

    for (int i = 0; i < src.Count; i++)
    {
        TValue value = (TValue)src[i].Clone();
        arr.Add(value); // No error.
    }

    return arr;
}

#3:使用Activator

但是,既然你想创建一个深度克隆,那么还有另一种方法,就是使用Activator.此方法不是类型安全的,并且当类型不支持该构造函数调用时可以生成运行时异常:

public static List<TValue> deepCopyList<TValue>(List<TValue> src)
{
    List<TValue> arr = new List<TValue>();

    for (int i = 0; i < src.Count; i++)
    {
        TValue value = (TValue)Activator.CreateInstance(typeof(TValue),src[i]);
        arr.Add(value);  // Possible runtime rror.
    }

    return arr;
}

上面的方法也可以通过使用反射替换并获取正确的ConstructorInfo并使用它来创建新项目.这与Activator的作用相同,并且具有相同的风险.

顺便说一句:在C#中,它被称为’通用’,而不是像C中那样的’模板’.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读