0

假设有一个枚举定义如下:

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]
4

3 回答 3

2

您可以将索引器应用于您的课程。

推荐使用,因为它改进了封装。例如,完全有可能使用原始代码将 Dictionary 完全替换为不同的字典——这可能是不可取的。

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];
于 2013-03-04T13:16:21.690 回答
1

您还可以使用索引器

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];

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

于 2013-03-04T13:20:02.957 回答
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

    }
}
于 2013-03-04T13:18:07.297 回答