如何以字符串格式保存Type
?
public class cat
{
public int i = 1;
public func ()
{
Console.WriteLine("I am a cat");
}
}
// ...
Type obj_type = typeof(cat);
string arg2;
arg2 = obj_type.ToString(); /* error*/
arg2 = (string)obj_type;/*same error*/
arg2 = obj_type.Name; /*same error*/
Console.WriteLine(obj_type); /*ok*/ " temp.cat "
我在上面一行收到此错误:
无法隐式转换类型'字符串'到' System.Type'
答案 0 :(得分:1)
如果您需要完全限定类型名称,请尝试:
arg2 = obj_type.AssemblyQualifiedName;
答案 1 :(得分:1)
您可以获取实例化对象的类型:
string typeName = obj.GetType().Name;
MSDN对GetType
方法的引用:https://msdn.microsoft.com/en-us/library/system.object.gettype(v=vs.110).aspx
如果您想通过Class获取Type name:
private static void ShowTypeInfo(Type t)
{
Console.WriteLine("Name: {0}", t.Name);
Console.WriteLine("Full Name: {0}", t.FullName);
Console.WriteLine("ToString: {0}", t.ToString());
Console.WriteLine("Assembly Qualified Name: {0}",
t.AssemblyQualifiedName);
Console.WriteLine();
}
答案 2 :(得分:0)
这很好用,只需检查一下:
Type obj_type = typeof(cat);
string arg2 = obj_type.ToString();
// arg2 = obj_type.Name; it works too and it gives short name without namespaces
Console.WriteLine(arg2);
输出:Test1.cat
//完全限定名称
P.S。
arg2 = (string)obj_type;
在这里,您尝试将Type显式转换为字符串。就像你说"嘿,我100%确定Type可以很容易地转换为字符串,所以就这样做了#34;。它没有用,因为它们之间没有简单的转换,编译器也不知道如何处理它。
答案 3 :(得分:0)
typeof接受一个Type而不是它的实例。
看到这个。
public class cat
{
public int i = 1;
public void func()
{
Console.WriteLine("I am a cat");
}
}
Type type = typeof(cat);// typeof accept a Type not its instance
string typeName = type.Name;// cat