0

我有以下代码,如果它有很多。我知道将字符串名称转换为类类型是类类型只能在运行时使用。

ViewType vtype;
Series sser = new Series();

       if (Convert.ToString(vtype) == "Bar")
        {
          ((DevExpress.XtraCharts.BarDrawOptions)sser.View).ColorEach = true;
        }
        else if (Convert.ToString(vtype) == "StackedBar")
        {
          ((DevExpress.XtraCharts.StackedBarSeriesView)sser.View).ColorEach = true;
        }
        else...

sser.DataSource = dtTable;

为了缩短我的代码,我想出了这个想法

Series sser = new Series();
string classtype = DevExpress.XtraCharts.Native.SeriesViewFactory.GetType(vtype).ToString();
//classtype returns a value 'DevExpress.XtraCharts.BarDrawOptions', 'DevExpress.XtraCharts.StackedBarSeriesView' etc
Type type = Type.GetType(classtype);
((type)sser.View).ColorEach = true;             
sser.DataSource = dtTable;

string classtype如果string classtype返回值我想DevExpress.XtraCharts.BarDrawOptions将字符串转换为其类类型并将其转换为sser.View

这有可能实现还是其他方式?

4

1 回答 1

0
//Use this Dictionary to pair the view types and their corresponding ColorEach to set accordingly
Dictionary<Type,bool> colorEaches = new Dictionary<Type,bool>();
colorEaches[typeof(DevExpress.XtraCharts.BarDrawOptions)] = true;
colorEaches[typeof(DevExpress.XtraCharts.StackedBarSeriesView)] = true;
//.....
bool value;
Type viewType = sser.View.GetType();
if(colorEaches.TryGetValue(viewType,out value)){
   //Suppose your `ColorEach` should be present in all the types added to the Dictionary
   viewType.GetProperty("ColorEach").SetValue(sser.View, value);
}else {
  //your own code
}
于 2013-09-03T06:13:28.880 回答