我已经声明了一个列表来动态创建我的类对象。
List<clsFormula> oFormula = new List<clsFormula>();
for (int i = 0; i < 4; i++)
{
oFormula.Add(new clsFormula());
}
当我想使用对象编号2中的函数时,我会编写像
这样的代码oFormula[2].FunctioName();
我的问题是:我可以直接在对象中定义名称而不是使用数字吗?所以它就像oFormula["StringName"].FunctionName()
;当我声明运行时对象时我应该使用什么样的代码?
答案 0 :(得分:1)
创建一个新的集合类型并从System.Collections.ObjectModel.KeyedCollection继承它。重写GetKeyForItem方法并返回clsFormula对象的名称。
http://msdn.microsoft.com/en-us/library/ms132438.aspx
public class clsFormulaCollection : KeyedCollection<string, clsFormula>
{
protected override string GetKeyForItem(clsFormula item)
{
return item.Name;
}
}
clsFormulaCollection oFormula = new clsFormulaCollection();
for (int i = 0; i < 4; i++)
{
oFormula.Add(new clsFormula());
}
oFormula["FormulaName"].SomeFunction();
答案 1 :(得分:0)
意识到它不是java,但是当我达到删除限制时将其打开。
如果是java。
List
保存数据并使用索引对其进行映射。根据您的要求,您需要使用java.util.Map
Map<String, clsForumla> map = new Map<String, clsForumla>();
map.put("firstObj",new clsForumla());
map.put("secondObj",new clsForumla());
map.put("thirdObj",new clsForumla());
//calling method on second object
map.get("secondObj").foo();
答案 2 :(得分:0)
List没有使用字符串参数的索引器。您可以从List<T>
继承并创建一个接受字符串的Indexer,您需要实现逻辑以查找并返回该项。
public class SampleList<T> : List<T>
{
public T this(string name)
{
get
{
//Find the Item and return.
}
}
}
答案 3 :(得分:0)
这段代码对我来说很好,
我为您的解决方案创建了一个示例应用程序,
我有一个如下课程,
public class ClsFormula
{
public ClsFormula()
{
}
public int Function1()
{
return 5 + 6;
}
}
现在我将这个类用于其中一个click事件,制作类对象的列表,
List<ClsFormula> clsformula = new List<ClsFormula>();
for (int i = 0; i < 4; i = i + 1)
{
ClsFormula objcls = new ClsFormula();
clsformula.Add(objcls);
}
MessageBox.Show(clsformula[2].Function1().ToString());
它适用于我。