我正在尝试对我的代码进行一些优化。我有enum
:
enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
以及带有现成类对象的以下代码:
oi.Jan = Math.Round(Convert.ToDecimal(adjAllocation[0]), 2).ToString();
oi.Feb = Math.Round(Convert.ToDecimal(adjAllocation[1]), 2).ToString();
oi.Mar = Math.Round(Convert.ToDecimal(adjAllocation[2]), 2).ToString();
oi.Apr = Math.Round(Convert.ToDecimal(adjAllocation[3]), 2).ToString();
oi.May = Math.Round(Convert.ToDecimal(adjAllocation[4]), 2).ToString();
oi.Jun = Math.Round(Convert.ToDecimal(adjAllocation[5]), 2).ToString();
oi.Jul = Math.Round(Convert.ToDecimal(adjAllocation[6]), 2).ToString();
oi.Aug = Math.Round(Convert.ToDecimal(adjAllocation[7]), 2).ToString();
oi.Sep = Math.Round(Convert.ToDecimal(adjAllocation[8]), 2).ToString();
oi.Oct = Math.Round(Convert.ToDecimal(adjAllocation[9]), 2).ToString();
oi.Nov = Math.Round(Convert.ToDecimal(adjAllocation[10]), 2).ToString();
oi.Dec = Math.Round(Convert.ToDecimal(adjAllocation[11]), 2).ToString();
我正在尝试这样做(伪代码):
oi.[Months[i]] = Math.Round(Convert.ToDecimal(adjAllocation[0]), 2).ToString();
我不能只在我正在制作对象的类中放入一个数组。我需要将属性作为我正在调用的现成类的字符串。
答案 0 :(得分:1)
有System.Enum
- 课程,提供辅助方法来支持enum
的使用。
例如,有Enum.GetName
- 方法来访问特定值。来自MSDN:
using System;
public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };
public static void Main() {
Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.Get. Name(typeof(Styles), 3));
}
}
// The example displays the following output:
// The 4th value of the Colors Enum is Yellow
// The 4th value of the Styles Enum is Corduroy
答案 1 :(得分:1)
这不是优化,而是简化的尝试。反思可以做到这一点,但似乎根本没有简化:
public enum Months {
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
}
public partial class SomeClass {
public String Jan { get; set; }
public String Feb { get; set; }
public String Mar { get; set; }
public String Apr { get; set; }
public String May { get; set; }
public String Jun { get; set; }
public String Jul { get; set; }
public String Aug { get; set; }
public String Sep { get; set; }
public String Oct { get; set; }
public String Nov { get; set; }
public String Dec { get; set; }
public SomeClass(IConvertible[] array) {
var count=(
from Months month in Enum.GetValues(typeof(Months))
let index=(int)month
where index<array.Length
select
typeof(SomeClass).InvokeMember(
Enum.GetName(typeof(Months), month),
BindingFlags.SetProperty|BindingFlags.Instance|BindingFlags.Public,
default(Binder), this,
new object[] { Math.Round(array[index].ToDecimal(null), 2).ToString() }
)
).Count();
}
}
如果数组adjAllocation
可以转换为十进制,那么它将是IConvertible
的数组。所以把它传递给SomeClass
的构造函数,你就完成了。