使用Math.Round转换特定对象类型的所有属性值?

时间:2016-10-14 11:04:34

标签: c#

我有一个具有这种结构的特定对象类型:

       String str1, str2;
       Scanner scan = new Scanner(System.in);

       System.out.print("Enter a String : ");
       str1 = scan.nextLine();
       str2 = str1.replaceAll("[aeiouAEIOU]", "?");
       // adding AEIOU to capture Vowels in uppercase.
       System.out.println("All Vowels Removed Successfully");

       System.out.println(str2);

现在调用一个特定的方法我得到这样的属性:

enter image description here

此值存储在此对象中:

public class PoissonFullTime
{
    public double HomeWin { get; set; } //1
    public double Draw { get; set; }  //X
    public double AwayWin { get; set; } //2
    public double HomeWinDraw { get; set; } //1X

可以迭代到var fullTimeForecast = poisson.GetFullTimeForecast(); 的每个属性并将值转换为fullTimeForecast吗?感谢。

4 个答案:

答案 0 :(得分:2)

反思将有助于解决您的问题,它将使用doublefiddle)更新类型为Math.Round的所有对象的属性:

var fullTimeForecast = new PoissonFullTime { AwayWin = 123.3123123 };
fullTimeForecast.GetType().GetProperties()
    .Where(x => x.PropertyType == typeof(double)).ToList()
    .ForEach(x => x.SetValue(
            fullTimeForecast, 
            Math.Round((double)x.GetValue(fullTimeForecast), 2)
        )
    );

答案 1 :(得分:1)

您应该使用自己的getter / setter而不是自动实现。

private double _homeWin;
public double HomeWin { 
    get { return _homeWin; } 
    set { this._homeWin = Math.Round(value, 2); }
} 

答案 2 :(得分:0)

使用属性:

private double a;
public double A {
    get { return Math.Round( a, 2); }
    set { a = value; }
}

答案 3 :(得分:0)

如果您希望在班级中使用具有确切值的属性,以计算确切的百分比,但是您希望以双倍百分比向用户显示这些属性,则可以使用反射执行此操作。

        PoissonFullTime obj = new PoissonFullTime();
        var propertyInfos = obj.GetType().GetProperties();

        foreach(var prop in propertyInfos)
        {
            prop.SetValue(obj, Math.Round((double)prop.GetValue(obj), 2));
        }

请注意反射具有性能成本。另一种方法是使用名为AlwaysWinRound的第二个属性。这将导致复制您的属性,您应该更改以前的属性。

private double _alwaysWin;

public double AlwaysWin
{
    get { return _alwaysWin; }
    set { _alwaysWin = value; }
}
public double AlwaysWinRound
{
    get { return Math.Round(_alwaysWinRound, 2); }
}
相关问题