开发者

Typecast to a type from just the string representation of the type name

开发者 https://www.devze.com 2022-12-27 03:51 出处:网络
sTypeName = ... //do some string stuff here to get the name of the type /* The Assembly开发者_StackOverflow.CreateInstance function returns a type
sTypeName = ... //do some string stuff here to get the name of the type

/*
The Assembly开发者_StackOverflow.CreateInstance function returns a type
of System.object. I want to type cast it to 
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

How do I do that? And, what do I take on the left side of the assignment expression, assuming this is C# 2.0. I don't have the var keyword.


Usually you let all classes, you want to instantiate this dynamically, implement a common interface, lets say IMyInterface. You can create an instance from the classname string like this:

Assembly asm = Assembly.GetExecutingAssembly();
string classname = "MyNamespace.MyClass";
Type classtype = asm.GetType(classname);

// Constructor without parameters
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype);

// With parameters (eg. first: string, second: int):
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype, 
                        new object[]{
                            (object)"param1",
                            (object)5
                        });

Even if you dont have a common interface, but know the name of the method (as string) you can invoke your methods like this (very similar for properties, event and so on):

object instance = Activator.CreateInstance(classtype);

int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance, 
                        new object[] { 15 });
// result = 30

The example class:

namespace MyNamespace
{
    public class MyClass
    {
        public MyClass(string s, int i) { }

        public int TwoTimes(int i)
        {
            return i * 2;
        }
    }
}


Unfortunately there's no way in .NET to do what you want.

Possible partial solutions are:

  1. If you know the type at compile-time (unlikely, since you're creating it at run-time from a string) then simply cast to that type:

    YourType t = (YourType)Activator.CreateInstance(sTypeName);
    
  2. If you know that all the possible types will implement a specific, common interface then you can cast to that interface instead:

    IYourInterface i = (IYourInterface)Activator.CreateInstance(sTypeName);
    

If you can't do either of the above then, unfortunately, you're stuck with object and reflection.


.

Define a generic method in your class, and then you can cast like this:

 public T Cast<T>(object obj)
 {
      return (T) obj;
 }

 string sTypename = "SomeClassName"; 
 MethodInfo cast = this.GetType().GetMethod("Cast");
 MethodInfo genericCast = cast.MakeGenericMethod(new Type[] { Type.GetType(sTypename) });
 Object castedValue = genericCast.Invoke(this, new object[] { instanceToBeCasted });

But then I think, what is the point of such casting if you cannot store the casted value in a variable of the actual type, precisely because you don't know the actual type at the time of writing the code?

0

精彩评论

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