开发者

Dictionary<string,Object> will not let me access the Object members

Considering:

Dictionary<string,Object> dict = new Dictionary<string,Object>();

dict.Add("Name","deadlock");
dict.Add("Birthday",new BD(12,12,1955));

Knowing that BD is:

public class BD {

public int Day {get; set; }
public int Month {get; set; }
public int Year {get; set;}

public BD(int x,int y,int z) { Day=x; Month=y; Year=z; }
}

My problem is that I can't reference Day,Month,Year from the dictionary like that:

int Day1 = dict["Birthda开发者_高级运维y"].Day;

The above code won't work. Any suggestions are welcome.


int Day1 = ((BD)dict["Birthday"]).Day;

You need to cast it into a BD object.


It doesn't work because dict["Birthday"] returns an Object of type Object

In order to use this as expected, you need to cast the object to an appropriate type.

if(dict["Birthday"] is BD)
{
  var bd = dict["Birthday"];
  bd.Day; //do something useful
}

//or
var bd = dict["Birthday"] as BD
if(bd != null)
{
  bd.Day; //something useful
}

However, what you are doing is a kludge. Collections are most effective when storing homogeneous types. By storing generic objects, you can certainly store mixed types, but you have the added responsibility of ensuring type safety before casting.


Although multiple data types are always in play on a variable or reference, the instance members are filtered through the eyes of only one data type (and what it inherited). Therefore the stated (declared) data type at a time. Then the compiler knows what data type of multiple it is dealing with at that point.

In your case any instance of BD is all of the types: BD and System.Object through inheritance. If any interfaces had been implemented then those would be additional data types that the instance is also.

However type Object only shows Object members (and what it inherited, which is nothing more) even if the data type BD is also part of it.

To explicitly state to the C# compiler your intention of what data type to use of multiple available, you will have to "downcast", cast and/or convert accordingly using one of the mechanisms in C#/.NET like: C# casting ((BD)dict["Birthday"]).Day;, explicit conversion between compatible reference types (dict["Birthday"] as BD).Day;. In the case of basic data types you can also use conversion e.g. System.Convert.ToInt32(myLongValue). More features exist in .NET to support conversion endeavours.


You need to cast the object to the type you want to use:

int Day1 = ((BD) dict["Birthday"]).Day;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜