C#-使用键从字典中获取值-对象的返回属性? [英] C# - Get value from dictionary with key - return property of object?
问题描述
我正在编写一个程序,当输入元素的化学符号时,它将把该元素的信息返回到表单上.这很简单,但是它想尝试使我的代码尽可能高效.
I'm making a program which when a chemical symbol of an element is entered, it'll return information of that element onto the form. This is simple to do but it want to try and keep my code as efficient as possible.
我的字典:
Dictionary<string, object> alkaliM = new Dictionary<string, object>();
在我的代码中:
alkaliM.Add("Li", new AlkaliMetals.Lithium());
elementSymbol
是我在文本框中输入的字符串
elementSymbol
is my input string from the textbox
我正在尝试将elementName.Text
设置为我的AlkaliMetals.Lithium
对象的属性"name
".但是,我不能简单地说:
I'm trying to set elementName.Text
to the property "name
" of my AlkaliMetals.Lithium
object. However, i can't simply put:
elementName.Text = alkaliM[elementSymbol.Text];
,因为我无法将对象设置为字符串. ("Cannot implicty convert type "object" to "string"
")
elementName.Text = alkaliM[elementSymbol.Text];
as i can't set an object as a string. ("Cannot implicty convert type "object" to "string"
")
有什么方法可以仅使用键将elementName.Text
设置为AlkaliMetals.Lithium.name
吗?
Is there any way to set elementName.Text
to AlkaliMetals.Lithium.name
using only the key?
我有一个单独的文件,该文件具有一个主类AlkaliMetals
和每个子类(如Lithium
)的子类.
I have a separate file that has a main class AlkaliMetals
and subclasses for each of the alkali metals like Lithium
.
如果我的描述不合理,请告诉我,我将尽力解释我的意思.
If my description doesn't make sense let me know and i'll try to explain what i mean.
推荐答案
您可以使AlkaliMetals.cs中的所有子类都实现一个抽象类CommonAbstractClass
具有属性name
You can make all the sub classes in AlkaliMetals.cs implement an abstract class CommonAbstractClass
having the property name
将字典定义为Dictionary<string, CommonAbstractClass>
然后按照以下说明使用字典elementName.Text = alkaliM[elementSymbol.Text].name;
Then use your dictionary as follows elementName.Text = alkaliM[elementSymbol.Text].name;
这篇关于C#-使用键从字典中获取值-对象的返回属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!