开发者

typeof & GetType

I serialize a class below and the method needs开发者_Python百科 object type as parameter.

string xml = SerializeObject(data, typeof(ClassData));

I think second parameter is not necessary. How can I remove the second parameter? How can I get type of data as Type ?


You can do:

data.GetType()

which would give you the type of data

The entire expression would be

string xml = SerializeObject(data, data.GetType());

GetType() is a method that is declared on Object and can be used on an instance of an object.

typeof() is a statement that can be used on a Type without having an instance of it.

// Get type from instance
Type type = data.GetType()

// Get type from Type
Type type = typeof(ClassData)


string xml = SerializeObject(data, data.GetType());

if you have

Person p = ... ;

to get the type, you can do

Type t = p.GetType()

if you need the runtime type of the object. p could be an object of a class that extends Person.

or

Type t = typeof(Person);


Use the following:

classData.GetType( );


data.GetType() should return the type object of the class of 'data'.


To get the type of data as Type, you can use this syntax:

Type dataType = data.GetType();

I hope that is what you are asking, as the question is not entirely clear to me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜