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

c# – 泛型参数的构造函数要求?

发布时间:2020-12-16 01:44:13 所属栏目:百科 来源:网络整理
导读:看看 this问题,我开始考虑如何处理C#中的构造函数需求. 假设我有: T SomeMethodT(string s) : where T : MyInterface{ return new T(s);} 我想在T上设置它可以用字符串构造的要求,但据我所知,构造函数定义不允许作为接口的一部分.有没有一种标准的解决方法
看看 this问题,我开始考虑如何处理C#中的构造函数需求.

假设我有:

T SomeMethod<T>(string s) : where T : MyInterface
{
    return new T(s);
}

我想在T上设置它可以用字符串构造的要求,但据我所知,构造函数定义不允许作为接口的一部分.有没有一种标准的解决方法?

解决方法

在接口中添加init方法或属性,

public interface MyInterface
{
    void Init(string s);
    string S { get; set; }
}

T SomeMethod<T>(string s) : where T : MyInterface,new()
{
    var t = new T();
    t.Init(s);

    var t = new T
    { 
        S = s
    };

    return t;
}

因为您不能指定构造函数约束的参数

(编辑:李大同)

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

    推荐文章
      热点阅读