简体   繁体   English

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

[英]How to save a Type in string format

How do I 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 "

I receive this error at the line above: 我在上面的行中收到此错误:

Cannot implicitly convert type 'string' to 'System.Type' 无法将类型'string'隐式转换为'System.Type'

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

arg2 = obj_type.AssemblyQualifiedName;

You can get type of instantiated object: 您可以获取实例化对象的类型:

string typeName = obj.GetType().Name;

MSDN reference to GetType method: https://msdn.microsoft.com/en-us/library/system.object.gettype(v=vs.110).aspx MSDN对GetType方法的引用: https : GetType ( v= GetType

And in case you want to get Type name just by Class: 并且如果您只想按类获取类型名称:

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

This works fine, just checked it : 正常工作,只需检查一下即可:

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

Output: Test1.cat // fully qualified name 输出: Test1.cat //完全限定的名称

PS 聚苯乙烯

arg2 = (string)obj_type;

Here you try to explicitly cast Type to string. 在这里,您尝试将Type显式转换为字符串。 It's like you say "Hey i am 100% sure that Type can be converted to string easily so just do it". 就像您说“嘿,我100%确定Type可以轻松转换为字符串,所以就做吧”。 It's not working because there is no simple conversion between them and compiler doesn't know how to handle it. 它不起作用,因为它们之间没有简单的转换,并且编译器也不知道如何处理它。

typeof accept a Type not its instance. typeof接受Type而不是其实例。

See This. 看到这个。

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