我有一个要在其中系统地转换值的属性,并且我有很多属性,因此没有以下内容:
class myClass
{
private Double _Length;
public Double Length { get { return convert(_Length); } set { _Length = convertBack(value); }}
private Double _Height;
public Double Height{ get { return convert(_Height); } set { _Height= convertBack(value); }}
private Double _Width;
public Double Width{ get { return convert(_Width); } set { _Width= convertBack(value); }}
...
Double convert(Double base_value) { do work to return converted_value; }
Double unconvert(Double converted_value) { to work to return base_value; }
}
我想做这样的事情以减少代码污染和冗余
class myBaseClass
{
class DoublePropertyConverter extends Property
{
public Double get { return convert(this); }
public Double set { this = unconvert(value); }
}
Double convert(Double base_value) { do work to return converted_value; }
Double unconvert(Double converted_value) { to work to return base_value; }
}
class myClass : public myBaseClass
{
[DoublePropertyConverter]
public Double Length { get; set;}
[DoublePropertyConverter]
public Double Height{ get; set;}
[DoublePropertyConverter]
public Double Width{ get; set;}
...
}
这是完全可能吗?
答案 0 :(得分:3)
没有办法按照您所描述的方式“扩展属性”。
但是创建一个新的类型很容易,它表示来自的转换和另外两个值。例如,DateTime
和TimeSpan
之类的类型只是long
的包装,它们为您处理转换为不同语义值的情况。老实说,听起来您应该应该使用新的类型,因为您拥有一种消费者希望以一种方式对待的价值,但实际上它在内存中被表示为其他东西,并且类型很棒在许多情况下只能做到这一点,而超出了获取和设置属性值的范围。
public class Foo
{
public Foo(double value)
{
underlyingValue = FromDouble(value);
}
private readonly object underlyingValue;
public double Value => ToDouble(underlyingValue);
public static implicit operator double(Foo foo) => ToDouble(foo.underlyingValue);
public static implicit operator Foo(double value) => new Foo(value);
private static double ToDouble(object underlyingVvalue)
{
throw new NotImplementedException();
}
private static object FromDouble(double value)
{
throw new NotImplementedException();
}
}
类型中的基础字段可以是您要与之进行相互转换的任何内容,然后可以在一个位置定义转换逻辑。