C# 关于属性的争论
假设存在如下定义的枚举:C# 关于属性的争论,c#,properties,C#,Properties,假设存在如下定义的枚举: public enum Beep { HeyHo, LetsGo } 我想知道是否有可能改善以下性能: public Dictionary<Beep, String> Stuff{ get; set; } ... String content = Stuff[Beep.HeyHo] public Dictionary Stuff{get;set;} ... String content=Stuff[Beep.HeyHo] 因为按照现在的方式,我
public enum Beep
{
HeyHo,
LetsGo
}
我想知道是否有可能改善以下性能:
public Dictionary<Beep, String> Stuff{ get; set; }
...
String content = Stuff[Beep.HeyHo]
public Dictionary Stuff{get;set;}
...
String content=Stuff[Beep.HeyHo]
因为按照现在的方式,我检索字典,然后选择我需要的元素。我想知道(a)是否可能,如果可能的话(b)建议创建这样的伪代码
public String Stuff{ get<Beep>; set<Beep>; }
...
String content = Stuff[Beep.HeyHo]
公共字符串填充{get;set;}
...
String content=Stuff[Beep.HeyHo]
您可以将应用程序应用于您的类
建议使用它,因为它改进了封装。例如,完全有可能使用原始代码将字典完全替换为不同的字典-这可能是不可取的
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?
}
你可以向你的班级申请
建议使用它,因为它改进了封装。例如,完全有可能使用原始代码将字典完全替换为不同的字典-这可能是不可取的
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?
}
像这样的使用
像这样的使用 您也可以使用 你可以打电话
var obj = new MyClass();
string result = obj[Beep.HeyHo];
索引器的工作方式与属性非常相似,但至少有一个参数用作索引。每个类只能有一个索引器,但是可以为它创建不同的重载。同样的规则适用于方法。您也可以使用
你可以打电话
var obj = new MyClass();
string result = obj[Beep.HeyHo];
索引器的工作方式与属性非常相似,但至少有一个参数用作索引。每个类只能有一个索引器,但是可以为它创建不同的重载。同样的规则也适用于方法。hmm也许你应该在这是一个枚举,与枚举器完全不同。你应该定义一个带有嘟嘟声参数的
索引器。
方法。hmm也许你应该在这是一个枚举,与枚举器完全不同枚举数。您应该定义一个采用Beep参数的索引器
方法。
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];