开发者

In what context is it good to use the typeof operator?

开发者 https://www.devze.com 2023-02-09 11:54 出处:网络
I don\'t understand when to use the typeof() operator? In what context开发者_JAVA百科 is it good to use it?It is like .GetType() except it works on a type name instead of an instance.

I don't understand when to use the typeof() operator? In what context开发者_JAVA百科 is it good to use it?


It is like .GetType() except it works on a type name instead of an instance.

You would use typeof(MyType) if you need to get an instance of System.Type and you know the type at compile time. You don't need an instance of that type for resolve the description of that type (System.Type).

Eg if you had an instance you would:

object o = new MyType();
Type type = o.GetType()

But you could:

Type type = typeof(MyType)


It gets you an instance of Type from a type.

I can get the assembly of which this class is in.

typeof(MyClass).Assembly


It is also used during .Net remoting when both Marshalling an object and also getting an object from an Activator.

When Marshalling an object you need to specify the interface the object exposes that you wish to marshal...

_pServerFileXFer = RemotingServices.Marshal(m_serverFileXFer, m_strURI, typeof(IServer));

And when getting an object from the remoting services...you need to specify what type of object you want to get:

IServer server = Activator.GetObject(typeof(IServer), m_txtURI.Text) as IServer;
0

精彩评论

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