开发者

How to use the type 'Type'

开发者 https://www.devze.com 2023-03-07 17:53 出处:网络
I know that I can use the type string as: string someString = \"This is my string\"; I am not sure how to use the type Type

I know that I can use the type string as:

string someString = "This is my string";

I am not sure how to use the type Type

Type someType = someString开发者_运维知识库.GetType();

How could I create a variable based on that type. I want to do something like

someType someOtherString = "here is another string";
//string 

In other words, how could I create a variable based on some type?


There are a few ways to go about this, but the simplest would be to use the Activator class.

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Example:

Type t = someClassInstance.GetType();
object o = Activator.CreateInstance(t);


Variable types have to be known at declaration time. You can declare a variable of type object and then dynamically create an instance of a type which you only know about at execution time, but you can't dynamically declare a variable like that.

The closest you could get would be to create a generic type and instantiate that using a type argument specified with reflection. Then you really would have a variable of the right type - but you wouldn't be able to do anything particularly useful with it.

It's important to distinguish between the type of a variable and the type of the object a variable's value may refer to. For example:

object foo = Activator.CreateInstance(someType);

will end up with a variable of type object, but the value of foo will be a reference to an instance of whatever type someType refers to.


Try

 var object = Activator.CreateInstance(myType);


Starting from C# 3 you can do:

var someOtherString = "here is another string";

This way you don't care what's the type, var is type "joker" and save you the need to know the type at declaration time.

Hope that's what you mean?


use Assembly.CreateInstance()

Type type = typeof(String);
Assembly asm = Assembly.GetExecutingAssembly();
object blah = asm.CreateInstance(type.FullName);
0

精彩评论

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