繁体   English   中英

如何以字符串格式保存类型

[英]How to save a Type in string format

如何以字符串格式保存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 "

我在上面的行中收到此错误:

无法将类型'string'隐式转换为'System.Type'

如果需要完全限定的类型名称,请尝试以下操作:

arg2 = obj_type.AssemblyQualifiedName;

您可以获取实例化对象的类型:

string typeName = obj.GetType().Name;

MSDN对GetType方法的引用: https : GetType ( v= GetType

并且如果您只想按类获取类型名称:

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();
}

正常工作,只需检查一下即可:

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 //完全限定的名称

聚苯乙烯

arg2 = (string)obj_type;

在这里,您尝试将Type显式转换为字符串。 就像您说“嘿,我100%确定Type可以轻松转换为字符串,所以就做吧”。 它不起作用,因为它们之间没有简单的转换,并且编译器也不知道如何处理它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM