C#的财产,是有可能得到周围没有定义设置(没有靠山变量)定义得到什么? [英] C# property, is it possible to get around defining get without defining set (no backing variable)?

查看:178
本文介绍了C#的财产,是有可能得到周围没有定义设置(没有靠山变量)定义得到什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有300的属性,没有后盾的变量的类,每个属性会返回一个十进制/双。



例如:

 公共小数MathValue {搞定;组; } 

现在你决定,这些值中的每一个应该是圆角。



我要寻找重构它而无需重写所有这些属性的最简单的方法。



东西,这相当于实际工作中:D:

 公共小数MathValue {{返回Math.Round(MathValue);}集; } 


解决方案

您可以创建一个伪装成一个新的值类型是一个小数,但返回舍入值。事情是这样的:

 结构RoundedDecimal 
{
公共十进制值{搞定;私人集; }

公共RoundedDecimal(十进制值):这个()
{
THIS.VALUE =价值;
}

公共静态隐运营商十进制(RoundedDecimal D)
{
返回Math.Round(d.Value);
}
}

在你的类中的每个属性应该是类型<$的C $ C> RoundedDecimal 而不是小数


Lets say you have a Class with 300 properties with no backing variables, each of those properties returns a decimal/double.

Example:

public decimal MathValue { get; set; }

Now you decided that each one of those values should be rounded.

I am looking for the simplest way to refactor this without having to rewrite all of those properties.

Something, of this equivalent that actually works :D:

public decimal MathValue { get {return Math.Round(MathValue);} set; }

解决方案

You could create a new value type that pretends to be a decimal, but returns the rounded value. Something like this:

struct RoundedDecimal
{
    public decimal Value { get; private set; }

    public RoundedDecimal(decimal value) : this()
    {
        this.Value = value;
    }

    public static implicit operator decimal(RoundedDecimal d)
    {
        return Math.Round(d.Value);
    }
}

Each property in your class should be of type RoundedDecimal instead of decimal.

这篇关于C#的财产,是有可能得到周围没有定义设置(没有靠山变量)定义得到什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆