2017-07-17 69 views

回答

0

對象是普通的數據類型,你可以這樣操縱它。

private object _classmember; 
    public object classmember 
    { 
     get { return _classmember; } 
     set 
     { 
      _classmember = value; 
      if (_classmember.GetType()==typeof(Boolean)) 
      { 
       //Do your stuff 
       MessageBox.Show("boolean"); 
      } 

      if (_classmember.GetType() == typeof(int)) 
      { 
       //Do your stuff 
       MessageBox.Show("int"); 
      } 

      if (_classmember.GetType() == typeof(double)) 
      { 
       //Do your stuff 
       MessageBox.Show("double"); 
      } 
       //Declare all the necessary datatypes like the above 
     } 
    } 

用法會像

 classmember = true; 
     classmember = 1; 
     classmember = 6.6; 
2

聲明爲object,可以在後來is測試:

public object MyProperty { get; set; } 

public void DoSomething() 
{ 
    if(MyProperty is bool) 
    { 
     bool mp = MyProperty as bool; 
     // do something with boolean type mp 
    } 
    else if(MyProperty is string) 
    { 
     string mp = MyProperty as string; 
     // do something wit string type mp 
    } 
    // .... 
} 

在Visual Studio的新版本(我認爲2015年版本以上),你可以結合類型檢查和演員:

public void DoSomething() 
{ 
    if(MyProperty is bool mp) 
    { 
     // do something with boolean type mp 
    } 
    else if(MyProperty is string mp) 
    { 
     // do something wit string type mp 
    } 
    // .... 
} 

與通用類相比,這種方法的好處是屬性類型可以在對象生命週期中更改。

-1

在大多數語言中都有Object數據類型,其中所有其他數據類型都從中繼承。

2

你可以使用一個通用類:

public class MyThing<T> 
{ 
    public T MyProperty { get; set; } 
} 

現在你說什麼類型將是當你創建類:

var myIntObject = new MyThing<int>(); 
var myStringObject = new MyThing<string>(); 

myIntObject.MyProperty = 5; 
myStringObject.MyProperty = "Hello world"; 
+0

我喜歡這種方法。但是,如果指定值的類型可能在對象生存期中發生更改,則它有限制。沒有OP告訴他更多關於他的用例的信息,我們就無法得知它。如果類型不會改變,那麼泛型方法是更清潔 –

+0

嗯,這是可能的,但我會假設,如果數據類型正在改變對象的生命週期,那裏有代碼味道可能需要修復。 – DavidG

+0

我完全同意 –

相關問題