关于属性的争论

时间:2013-03-04 13:10:34

标签: c# properties

假设枚举定义如下:

public enum Beep
{
  HeyHo,
  LetsGo
}

我想知道是否可以改善以下属性:

public Dictionary<Beep, String> Stuff{ get; set; }
...
String content = Stuff[Beep.HeyHo]

因为它现在的方式,我检索字典,然后选择我需要的元素。我想知道它是否可能(a)可能,如果是这样的话(b)建议创建类似 - 代码的东西。

public String Stuff{ get<Beep>; set<Beep>; }
...
String content = Stuff[Beep.HeyHo]

3 个答案:

答案 0 :(得分:2)

您可以在课堂上申请indexer

建议,因为它改善了封装。例如,完全可以使用原始代码完全用不同的字典替换字典 - 这可能是不可取的。

public class MyClass
{
    // Note that dictionary is now private.
    private Dictionary<Beep, String> Stuff { get; set; }

    public String this[Beep beep]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal dictionary. 
            return this.Stuff[beep];
        }
        set
        {
            this.Stuff[beep] = value;
        }
    }

    // Note that you might want Add and Remove methods as well - depends on 
    // how you want to use the class. Will client-code add and remove elements,
    // or will they be, e.g., pulled from a database?
}

用法:

MyClass myClass = new MyClass();
string myValue = myClass[Beep.LetsGo];

答案 1 :(得分:1)

您还可以使用indexer

class MyClass
{
    private readonly Dictionary<Beep, string> _stuff = new Dictionary<Beep, string>();

    public string this[Beep beep]
    {
        get { return _stuff[beep]; }
        set { _stuff[beep] = value; }
    }
}

现在,而不是调用

var obj = new MyClass();
string result = obj.Stuff[Beep.HeyHo];

你可以打电话

var obj = new MyClass();
string result = obj[Beep.HeyHo];

索引器的工作方式与属性非常相似,但至少有一个参数用作索引。每个类只能有一个索引器,但是您可以创建不同的重载。相同的overloading规则适用于方法。

答案 2 :(得分:0)

使用Indexer

这样的事情
public class Stuff
{
    public Dictionary<Beep, String> _stuff { get; set; }
    public enum Beep
    {
        HeyHo,
        LetsGo
    }

    public Stuff()
    {
        _stuff = new Dictionary<Beep, string>();
        // add item
        _stuff[Beep.HeyHo] = "response 1";
        _stuff[Beep.LetsGo] = "response 2";
    }

    public string this[Beep beep]
    {
        get { return _stuff[beep]; }
    }
}

样本用法:

public static class Program
{
    private static void Main()
    {
        Stuff stuff = new Stuff();

        string response;
        response = stuff[Stuff.Beep.HeyHo]; // response 1
        response = stuff[Stuff.Beep.LetsGo]; // response 2

    }
}