Cast from unknown type in c#

后端 未结 2 1163
终归单人心
终归单人心 2021-01-22 19:58

I have a object that contain a value in string and a origin Type that is in a field.

class myclass
{
   public string value;
   public Type type;
}
myclass s=new         


        
2条回答
  •  粉色の甜心
    2021-01-22 20:29

    Basically your scenario is that you want to type cast with the type stored in a variable. You can only do that at runtime like this :

        myclass s=new myclass();
        s.value = "10";
        s.type = typeof(int);
    
        var val = Convert.ChangeType(s.value, s.type);
    

    but since the conversion is done at runtime, you cannot store the variable val in any integeral collection i.e. List or even you cannot do int another = val, coz at complie time, the type is not known yet, and you will have compilation error, again for same obvious reason.

    In a little complex scenario, if you had to typecast to a User-Defined dataType and you wanted to access its different properties, you cannot do it as is. Let me demonstrate with few modifications to your code :

    class myclass
    {
        public object value;
        public Type type;
    }
    

    and you have another:

        class myCustomType
        {
            public int Id { get; set; }
        }
    

    now you do :

     myclass s = new myclass();
     s.value = new myCustomType() { Id = 5 };
     s.type = typeof(myCustomType);
     var val = Convert.ChangeType(s.value, s.type);
    

    now if you do val.Id, it won't compile. You must retrieve it either by using dynamic keyword or by reflection like below:

     var id = val.GetType().GetProperty("Id").GetValue(val);
    

    you can iterate over all the available properties of your customType (class) and retrieve their values.

    for retrieving it through dynamic keyword, directly do this:

    dynamic val = Convert.ChangeType(s.value, s.type);
    int id = val.Id;
    

    and compiler won't cry. (Yes there won't be any intellisense though)

提交回复
热议问题