2010-01-27 50 views
2

基本上我想要生成的其他隨機值與給定值的值不同。如何以乾淨的方式爲原始類型實現擴展屬性類?

我以某種方式不能很好地掌握原始類型。

原始類型是Boolean,Byte,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single。

這裏基本上是我想要做的。

int oldValue = 1; 
    oldValue.Other(); // 2 

    long oldValue = 1; 
    oldValue.Other(); // 2 

    string oldValue = "1"; 
    oldValue.Other(); "5" 

有人建議我怎麼能解決這個很好?

回答

4

有一個名爲ValueType的基類。問題在於,使用它時需要將值轉換爲孩子。

e.g

int a =3; 
int b = (int)a.abc(); 

擴展的樣子以下

public static class ValueTypeExtension 
{ 
    public static ValueType abc(this ValueType a) { 

     return default(ValueType); 
    } 
} 

,你必須在參數進行類型檢查「一」的,如果elseif的正確返回值,你打算。

e.g

if(a is Int32) 
     return 4; 

更新: 字符串是不完全是一個值類型,但它當作一個。你仍然需要用獨立的擴展方法處理字符串。

0

根據你的問題,你想把原始類型作爲引用類型,這是不可能的(只能通過ref關鍵字)。爲了說明這一點,考慮以下因素:

int DoSomething(int n) 
{ 
    n = 5; 
    return n; 
} 

int a = 3; 
DoSomething(a); // a is still 3 
a = DoSomething(a); // a is now 5 

因此,這不會工作打算:

int oldValue = 1; 
oldValue.Other(); // oldValue won't change 

但這會:

int oldValue = 1; 
oldValue = oldValue.Other(); 
0

對於值類型,這將不工作。您需要將新值重新分配給變量。 例如:

int oldValue = 1;

oldvalue = oldValue.Other(); // 2

long oldValue = 1;

oldvalue = oldValue.Other(); // 2

string oldValue =「1」;

oldvalue = oldValue.Other(); 「5」

即使它們是引用類型,您也必須這樣做,因爲它們是不可變的(沒有辦法在不使用不安全指針黑客的情況下更改字符串)

相關問題