My method looks like:
public string DoObjectProperties<T>(T obj, string text)
{
}
Now from within the method, I need to get the string value of the class name that i pass 开发者_StackOverflow中文版into the method's 'obj' parameter.
So if I pass in the User object, I need the text 'user'.
To get the properties I am using: typeof(T).GetProperties()
How can I get the classes name?
Just use .Name
like this:
typeof(T).Name
This gives for example "String", there's also .FullName
which would give "System.String"
obj.GetType().Name;
//Returns "ObjectName"
Works if your method is deep into a generic method chain, as long as obj was defined at the top of the chain.
typeof(T).Name;
//Returns "T" if the method calling it also is generic.
This only works if the calling method defined the Class of T.
typeof(T).Name
?
typeof(T).Name //would work
But depending on it and making decisions based on it is probably not a good idea.
The important rule here is that you probably should use the FullName whenever possible.
For instance in switch case statements or in if else blocks or in dictionary keys.
Class name is not the ideal thing to depend on as you can potentially have same class name in different namespaces. NamespaceA.String and NamespaceB.String is perfectly possible...
精彩评论