cast object with a Type variable

前端 未结 5 1956
暗喜
暗喜 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条回答
  •  旧时难觅i
    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 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.

提交回复
热议问题