簡體   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