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

C# 如何以字符串格式保存类型,c#,C#,如何以字符串格式保存类型 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

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

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
方法的引用:

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

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

附言


在这里,您尝试显式地将类型强制转换为字符串。就像你说的“嘿,我100%确信类型可以很容易地转换成字符串,所以就这么做吧”。它不起作用,因为它们之间没有简单的转换,编译器不知道如何处理它。

typeof接受一个类型而不是它的实例

看这个

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

这不是错误发生的地方。这将编译并运行。标记为错误的行肯定没有给出错误。您可能正在将字符串传递给一个需要类型的方法。如果函数需要
类型
,那么您不能只传递它
字符串
,这样做没有什么神奇之处。我可以问一下,为什么您甚至试图将类型作为字符串传递?您对
CreateInstance
的使用让我觉得您是在寻找泛型,您在哪里使用
arg2
?到目前为止,您还没有显示字符串的使用位置,错误的实际来源是什么。
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