【问题标题】:How to avoid typing the object name for each property? [duplicate]如何避免为每个属性键入对象名称? [复制]
【发布时间】:2019-03-19 18:21:42
【问题描述】:

Class1 是一个已经实例化的类对象。是否有任何替代方法不每次都输入Class1.

Class1.Hostname = location.Ip;
Class1.UserName = location.Username;
Class1.Password = location.Password;
Class1.Port = 23;
Class1.GiveUpSecurityAndAcceptAnySshHostKey = true;
Class1.LogPath = "";
Class1.IsDebug = true;
Class1.Downloadwaitmiliseconds = 1000;

【问题讨论】:

标签: c#


【解决方案1】:

你可以这样做:

Class1 = new Class() 
{ 
  Hostname = location.Ip;
  UserName = location.Username;
  Password = location.Password;
  Port = 23;
  GiveUpSecurityAndAcceptAnySshHostKey = true;
  LogPath = "";
  IsDebug = true;
  Downloadwaitmiliseconds = 1000;

  AlreadySetPropety1 = Class1.AlreadySetPropety1;
  AlreadySetPropety2 = Class1.AlreadySetPropety2;
  …
}

这意味着您必须沿着您的属性设置已经设置的属性,但实际上您的代码中没有问题。例如,如果您个人不喜欢,可以将其重构为某种方法。

【讨论】:

【解决方案2】:

如果您想在实例化后设置属性,您可以创建一个将这些作为值作为参数的方法,并将它们设置在方法内部,您不需要变量名。 就像一个 Fill 方法。与您在类的构造函数中所做的相同。

如果您能够在实例化期间执行此操作,您可以执行类似的操作

var Class1= new YOURCLASS{
    Hostname = location.Ip;
    UserName = location.Username;
    Password = location.Password;
    Port = 23;
    GiveUpSecurityAndAcceptAnySshHostKey = true;
    LogPath = "";
    IsDebug = true;
    Downloadwaitmiliseconds = 1000;
};

【讨论】:

    【解决方案3】:

    您可以在Class1 中添加一个 set 方法,例如:

    class Class1 {
        public string Hostname { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public int Port { get; set; }
        public bool GiveUpSecurityAndAcceptAnySshHostKey { get; set; }
        public string LogPath { get; set; }
        public bool IsDebug { get; set }
        public int Downloadwaitmiliseconds { get; set; }
    
        public void setValues(string hostname, string username, string password, int port /* adding other values*/) 
        {
            Hostname = hostname;
            Username = username
            Port = port;
            /* The other values */
        }
    
    }
    

    如果你已经初始化了对象,也许是这样做的方法

    【讨论】:

      【解决方案4】:

      我知道没有语法可以做到这一点。您也许可以按照以下方式编写 Setter:

      public void Set(hostname = null, username = null, password = null)
      {
          if (hostname != null)
              Hostname = hostname;
          if (username != null)
              Username = username ;
          ...
      }
      

      您可以使用显式参数调用它:

      Class1.Set(hostname="localhost", username="me")
      

      当然,这仅在 null 不是您的属性的有效选项时才有效

      【讨论】:

        猜你喜欢
        • 2013-02-23
        • 2019-11-23
        • 2015-06-14
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 2011-09-08
        • 1970-01-01
        相关资源
        最近更新 更多