问题
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.
My dictionary:
Dictionary<string, object> alkaliM = new Dictionary<string, object>();
In my code also:
alkaliM.Add("Li", new AlkaliMetals.Lithium());
elementSymbol
is my input string from the textbox
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];
as i can't set an object as a string. ("Cannot implicty convert type "object" to "string"
")
Is there any way to set elementName.Text
to AlkaliMetals.Lithium.name
using only the key?
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.
回答1:
You can make all the sub classes in AlkaliMetals.cs implement an abstract class CommonAbstractClass
having the property name
Define you dictionary as Dictionary<string, CommonAbstractClass>
Then use your dictionary as follows elementName.Text = alkaliM[elementSymbol.Text].name;
回答2:
You can find the name
property (if you are absolutely sure it exists) using dynamic cast:
elementName.Text = (alkaliM[elementSymbol.Text] as dynamic).name
However, a more efficient approach would be Object Oriented Design
:
Define a class named ChemicalElement
, add name
property to it and then derive Lithium
from ChemicalElement
. This way you can write:
elementName.Text = (alkaliM[elementSymbol.Text] as ChemicalElement).name
Best solution is to define your dictionary like this:
Dictionary<string, ChemicalElement> alkaliM = new Dictionary<string, ChemicalElement>();
And then access the name
like:
elementName.Text = alkaliM[elementSymbol.Text].name
来源:https://stackoverflow.com/questions/48952148/c-sharp-get-value-from-dictionary-with-key-return-property-of-object