问题描述
我想建立一个接受一个字符串参数的方法,一个我想返回一个基于参数的特定成员的对象。因此,最简单的方法是构建一个switch语句:
I want to build a method which accepts a string param, and an object which I would like to return a particular member of based on the param. So, the easiest method is to build a switch statement:
public GetMemberByName(MyObject myobj, string name)
{
switch(name){
case "PropOne": return myobj.prop1;
case "PropTwo": return myobj.prop2;
}
}
这工作正常,但我可能会结束一个相当大的列表...所以我好奇,如果有一种方式,没有编写一堆嵌套的if-else结构,以索引的方式完成这一点,以便通过索引找到匹配字段,而不是通过交换机找到,直到找到了一个匹配。
This works fine, but I may wind up with a rather large list... So I was curious if there's a way, without writing a bunch of nested if-else structures, to accomplish this in an indexed way, so that the matching field is found by index instead of falling through a switch until a match is found.
我考虑使用 Dictionary< string,something>
来快速访问匹配的字符串(作为键成员),但是由于我想要访问一个传入对象的成员,我不知道这可以如何实现。
I considered using a Dictionary<string, something>
to give fast access to the matching strings (as the key member) but since I'm wanting to access a member of a passed-in object, I'm not sure how this could be accomplished.
-
我专门设法避免反射等等,以实现非常快速的实现。我可能会使用代码生成,所以解决方案不需要很小/紧密等。
I'm specifically trying to avoid reflection etc in order to have a very fast implementation. I'll likely use code generation, so the solution doesn't need to be small/tight etc.
我最初正在构建一个字典,但每个对象正在初始化它。所以我开始把它移到一个可以根据键 - 一个switch语句查找值的单一方法。但是,由于我不再索引,我恐怕连续查找调用这个方法会很慢。
I originally was building a dictionary of but each object was initializing it. So I began to move this to a single method that can look up the values based on the keys- a switch statement. But since I'm no longer indexed, I'm afraid the continuous lookups calling this method would be slow.
SO:我正在寻找一种将索引/散列查找(如Dictionary使用)的性能与返回特定属性的方法相结合,在对象中。我可能会在每个类中使用静态方法。
SO: I am looking for a way to combine the performance of an indexed/hashed lookup (like the Dictionary uses) with returning particular properties of a passed-in object. I'll likely put this in a static method within each class it is used for.
推荐答案
这是一个简单的方法可以使用字典:
Here's an easy way you can use a dictionary:
Dictionary<string, Func<MyObject, object>> propertyNameAssociations;
private void BuildPropertyNameAssociations()
{
propertyNameAssociations = new Dictionary<string, Func<MyObject, object>>();
propertyNameAssociations.Add("PropOne", x => x.prop1);
propertyNameAssociations.Add("PropTwo", x => x.prop2);
}
public object GetMemberByName(MyObject myobj, string name)
{
if (propertyNameAssociations.Contains(name))
return propertyNameAssociations[name](myobj);
else
return null;
}
这篇关于索引开关语句,还是等价的? .net,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!