cast object with a Type variable

前端 未结 5 1925
暗喜
暗喜 2020-11-30 10:59

The following doesn\'t work, of course. Is there a possible way, which is pretty similar like this?

Type newObjectType = typeof(MyClass);

var newObject = gi         


        
5条回答
  •  北海茫月
    2020-11-30 11:46

    You can use Convert.ChangeType. According to msdn, it

    returns an object of a specified type whose value is equivalent to a specified object.

    You could try the code below:

    Type newObjectType = typeof(MyClass);
    
    var newObject = Convert.ChangeType(givenObject, newObjectType);
    

提交回复
热议问题