2011-02-11 61 views
3

我有一種類型是這樣的:如何將對象值轉換爲Type值?

public class TypeValue 
{ 
    public Type Type { get; private set; } 
    public object Value { get; private set; } 
} 

,所以我可以做這樣的事情:

TypeValue tv = ... 
int count = (tv.Type) tv.Value; 

但編譯器給我這個錯誤:

The type or namespace name 'tv' could not be found (are you missing a using directive or an assembly reference?)

如何實現這個?

+0

謝謝,但爲什麼呢?類型不是關鍵字,對吧? – 2011-02-11 23:34:14

+0

在你的例子中,你知道'count'是一個int,因爲你剛剛聲明瞭它。 – 2011-02-11 23:41:22

+0

同意這一點。我必須考慮這一點,但我可能不需要這種演員。雖然我仍然感到驚訝,但我無法做到上述事情。例如,我怎麼能存儲「int」,所以它可以放在像上面的代碼?我想這是無法完成的。因爲如果「(type)value」正在使用實際的System.Type值,那麼它仍然會工作,因爲它會在編譯時知道,不是嗎? – 2011-02-11 23:52:48

回答

1

你應該只是做:

TypeValue tv = ... 
int count = (int) tv.Value; 

在編譯時知道該類型的情況下(在這種情況下,您知道countint),那麼無論如何都沒有意義指向tv.Type。這有助於說明爲什麼這不合邏輯,因此是不可能的。

3

不可以。編譯器如何在編譯時確定「類型」引用的類型? 「類型」對象與執行演員時使用的類型名稱不同。例如,這並不工作之一:

// "typeof" returns a "Type" object. 
string foo = (typeof(string))SomeObj; 

您將無法使用靜態演員,但你可以偷偷摸摸做這個using reflection at runtime.

+0

那我該如何做運行時強制轉換? – 2011-02-11 23:32:03

1

不可能從System.TypeSystem.Object得到強類型變量。有時你可以讓你的班級像這樣:

public class TypeValue<T> 
{  
    public T Value { get; private set; } 
} 
3

你所顯示的作業不能按照你想要的方式完成。 賦值運算符任一側的對象類型必須相同(或右側對象必須是繼承左側對象類型的類型)。

所以,你不能做

Type1 obj1 = new Type1(); 
Type type = typeof(Type1); 
Type2 obj2 = (type)obj1; 

你可以達到你想通過你的類通用的,或具有獲得價值泛型方法的功能。 例如

public class TypeValue 
{ 
    public Type Type { get; private set; } 
    public object Value { get; set; } 

    public T GetValueAs<T>() 
    { 
     if (Value == null) 
      return default(T); 
     return (T)Value; 
    } 
} 

TypeValue a = new TypeValue(); 
a.Value = 1; 
int b = a.GetValueAs<int>(); 

甚至更​​好

public class TypeValue<T> 
{ 
    public Type Type { get { return typeof(T); } } 
    public T Value { get; set; } 
} 

TypeValue<int> a = new TypeValue<int>(); 
a.Value = 1; 
int b = a.Value; 
Type c = a.Type; 
相關問題