【问题标题】:Understanding Property in C# [duplicate]了解 C# 中的属性 [重复]
【发布时间】:2013-12-29 12:27:34
【问题描述】:

我在浏览一个示例 C# (WPF) 代码时遇到了以下代码块:

public string this[string columnName]
{
    get
    {
        if (columnName == "FirstName") {
             return string.IsNullOrEmpty(this.firstName) ? "Required value" : null;
         }
         if (columnName == "LastName") {
             return string.IsNullOrEmpty(this.lastName) ? "Required value" : null;
         }
         return null;
    }
}

此代码块用于执行数据验证。从外观上看,它看起来像一个属性,因为它包含一个 get{} 块。只想了解语法的语义含义:

public string this[string columnName]

【问题讨论】:

标签: c# .net wpf


【解决方案1】:

那些被称为Indexers

索引器允许对类或结构的实例进行索引,就像 数组。索引器类似于属性,只是它们的访问器采用 参数。

说类名是TestClass。它允许这样做:

TestClass testObject = new TestClass();
string firstName = testObject["FirstName"];

一个可能的例子Dictionary,它在内部使用索引器。它允许您从对应于关键元素的字典中获取值:

Dictionary<int,string> dict = new Dictionary<int,string>();
dict.Add(1, "Test1");
string value = dict[1]; // value will be Test1.

【讨论】:

    【解决方案2】:

    这意味着您可以通过索引遍历“This”。例如,如果类的名称是 IndexClass,您可以这样做:

    IndexClass IC = new IndexClass();
    string name= IC["FirstName"];
    string name2=IC["LastName"];
    

    这个索引器返回一个字符串并且是字符串类型。您只能在 [] 中对一个字符串进行右移,而不能对任何其他类型。

    【讨论】:

      【解决方案3】:

      Indexers 允许您向类添加索引器并使用index 类似数组访问它的元素。所有集合都使用索引器,您也可以在创建自己的集合时使用它。

      但取决于您的代码,也可以使用属性来完成:

      public string FirstName 
      { 
         get { return string.IsNullOrEmpty(this.firstName) ? "Required value" : null; } 
      }
      
      public string LastName 
      { 
        get { return string.IsNullOrEmpty(this.firstName) ? "Required value" : null; } 
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-19
        • 2021-03-31
        • 1970-01-01
        • 2011-09-27
        • 2014-05-16
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        相关资源
        最近更新 更多