cast object with a Type variable

前端 未结 5 1920
暗喜
暗喜 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:38

    Maybe you can solve this using generics.

    public void CastToMyType<T>(object givenObject) where T : class
    {
       var newObject = givenObject as T;
    }
    
    0 讨论(0)
  • 2020-11-30 11:44

    You can check if the type is present with IsAssignableFrom

    if(givenObject.GetType().IsAssignableFrom(newObjectType))
    

    But you can't use var here because type isn't known at compile time.

    0 讨论(0)
  • 2020-11-30 11:44

    I recently had the case, that I needed to generate some code like in Tomislav's answer. Unfortunately during generation time the type T was unknown. However, a variable containing an instance of that type was known. A solution dirty hack/ workaround for that problem would be:

    public void CastToMyType<T>(T hackToInferNeededType, object givenObject) where T : class
    {
       var newObject = givenObject as T;
    }
    

    Then this can be called by CastToMyType(instanceOfNeededType, givenObject) and let the compiler infer T.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-30 11:52

    newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.

    This should work

    var newObject = givenObject as MyClass;
    

    OR

    var newObject = (MyClass) givenObject;
    

    Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.

    The only way var can work is that the type of the variable is known at compile-time.


    UPDATE

    Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.

    Type Conversion is a runtime concept.


    UPDATE 2

    If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.

    object myString = "Ali";
    Type type = myString.GetType();
    MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First();
    object invoked = methodInfo.Invoke(myString, null);
    Console.WriteLine(invoked);
    Console.ReadLine();
    
    0 讨论(0)
提交回复
热议问题