2017-07-17 85 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

我完全同意 –

相关问题