目前我正在尝试实现一个系统或一种创建类型的方法,但也在创建时获取类型名称。
假设我有这样的操作,可以由应用程序的用户创建:
Blur
Contrast
Sharpen
Diffuse
Invert
...
那么当通过 UI 创建它们时,我应该如何提取它们的名称。假设每个按钮都有单独的 UI 按钮。每次创建其中一个时,它们都必须命名为 Blur01
、Blur02
...这些对象将被创建数以百万计。
因此,目前它们具有必须在创建时设置的 .Name
属性。但我也不想在每个类中重复设置名称的代码。
我应该使用什么设计模式?
最佳答案
如果您希望每种类型都有其自己的、唯一的增量器,那么您将拥有重复的代码。您可以通过反射在具有 Type 和 int 的基类中保存静态字典来避免这种情况...类似于:
private static Dictionary<Type,int> nameSuffixCounters =
new Dictionary<Type,int>();
public string CreateName()
{
Type type = this.GetType();
return string.Format("{0}{1}",type.Name, this.GetNextAndIncrement(type));
}
private int GetNextAndIncrement(Type type)
{
int current;
if (!this.nameSuffixCounters.TryGetValue(type, out current))
{
current = 0;
}
nameSuffixCounters[type] = ++current;
return current;
}
这样的事情可以消除重复的代码,但它增加了在基类中使用反射的一些复杂性......
关于c# - 解决这个问题的最佳设计模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/762103/