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

c# – 有没有办法指定where T:new()限制但是内部构造函数?

发布时间:2020-12-15 08:24:28 所属栏目:百科 来源:网络整理
导读:我已经创建了一个需要实例化其实现类型的泛型类,因此实现类型必须具有可访问的参数而不是构造函数.看起来new()限制可以完成这项工作,但是当我将其设置为内部时,它强制执行类型以具有公共构造函数(但是两者都在同一个程序集中可访问). 有理由强迫它公开而不是
我已经创建了一个需要实例化其实现类型的泛型类,因此实现类型必须具有可访问的参数而不是构造函数.看起来new()限制可以完成这项工作,但是当我将其设置为内部时,它强制执行类型以具有公共构造函数(但是两者都在同一个程序集中可访问).

>有理由强迫它公开而不是“可访问”吗?
>有办法做我需要的吗?

提前致谢.

编辑:这样做的原因是我有一个必须通过Singleton使用的类X. Singleton类是一个泛型类,我想使类X构造函数内部避免外部用户以错误的方式访问对象(调用构造函数).

解决方法

如规范绑定和未绑定类型的4.4.3部分所述,C#语言不允许这样做.

If the constraint is the constructor constraint new(),the type A must not be abstract and must have a public parameterless constructor. This is satisfied if one of the following is true.

  • A is a value type,since all value types have a public default constructor
  • A is a type parameter having the cosntructor constraint
  • A is a type parameter having the value type constraint
  • A is a class that is not abstract and contains an explicitly declared public constuctor with no parameters
  • A is not abstract and has a default constructor.

如果不满足任何一个条件,则编译器错误.如果您发现自己的类型是公共的但只有内部构造函数,那么它们很可能实际上应该是具有公共构造函数的内部类型.

我建议将内部及其构造函数的类型访问器更改为public,并使其无参数.然后,您的公共无参数构造函数可以调用非参数的私有或内部构造函数来执行任何其他初始化工作.

internal class C<T> where : T new()
{
    public C() : this(new T()) {
    }

    private C(T t) {
        // Do additional initialization
    }
}

请注意,模式是有限的,但没有什么能阻止您使用私有方法.

internal class C<T> where T : new() {
    public C() {
        T t = new T();
        InitializeClass(t);
    }

    private void InitializeClass(T t) {
        throw new NotImplementedException();
    }
}

根据您的更新,这是一个公共单例模式的小例子.

public class Singleton<T> where T : new()
{
    public static Singleton<T> Current {
        get;
        private set;
    }

    internal Singleton() : this(new T()) {
    }

    private Singleton(T t) {
        Current = this;
        // Do whatever you need to with T
    }        

    public String Name {
        get;
        set;
    }
}

用法

// Somewhere in your internal assembly
Singleton<String> singleton = new Singleton<String>();

// In an external assembly
Singleton.Current.Name = "SoMoS";

你甚至不需要以这种方式使用构造函数,你可以轻松地做一些简单的事情.

public class Singleton<T> where T : new()
{
    public static Singleton<T> Current {
        get;
        private set;
    }

    internal Singleton() {
        T t = new T();
        // Do stuff with T
    }

    public String Name {
        get;
        set;
    }
}

如果你不能设计它以满足你的要求,泛型可能不是你要走的路.泛型只能做很多事情并且不能解决所有问题.有工厂模式,注塑等等.

(编辑:李大同)

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

    推荐文章
      热点阅读