繁体   English   中英

与私有构造函数的奇怪的intellisense行为

[英]Weird intellisense behavior with private constructor

例:

public class Name {

    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    private Name() { }

    public Name(string firstName, string lastName) {

        FirstName = firstName;
        LastName = lastName;

    }  
}

当试图实例化这个c#类时,intellisense会显示new关键字的私有和公共构造函数,即使其中一个构造函数是私有的!

更奇怪的是,当我从公共构造函数中删除第二个参数时(删除lastName作为公共构造函数的参数),intellisense现在只显示带有new关键字的公共构造函数。

这是一个错误还是我错过了什么? 我正在使用VS2008 SP1。

编辑:代码清晰度

哇,这很奇怪。 我只是在我的VS2008副本上尝试过它(我也在运行SP1)并且得到了完全相同的结果。 当有多个参数时,私有构造函数出现在Intellisense中,但不会出现在只有一个参数时。 我的猜测是,这是一个错误。

不知道为什么intellisense会向你展示奇怪的东西。 但是,对于具有公共构造函数的域对象,您应该有一个抽象基类,因此您不必使用私有对象来处理对象。 你也应该把你的主要属性等东西放在那里。

public abstract class BaseDomainObject{
  public BaseDomainObject() { }

  private int _id;

  public virtual int Id { get { return _id; } set { _id = value; } }

}

public SomeDomainObject : BaseDomainObject{
  ...
}

这可能是一个错误,但不值得努力修复。 也就是因为有很多场景访问私有构造函数是合法的。 请使用以下代码段。 所有私有构造函数访问都是合法的

class Outer {
  private Outer() {
  }
  public Outer Create() { return new Outer(); }
  class Inner() { 
    void Function1() { new Outer(); }
    class DoubleInner() {
       void Function2() { new Outer(); }
    }
  }
}

即使私有构造函数出现在Intellisense中,如果您尝试编译在不允许的情况下使用它的代码,编译器仍将通过“由于保护级别而无法访问”错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM