首页 > 解决方案 > 有没有办法在 C# 中派生或扩展属性?

问题描述

我有一个属性,我想系统地转换值,并且我有一个非常大的属性集,所以没有以下内容:

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;}

...

}

这是可能的吗?

标签: c#propertiesextending

解决方案


没有办法以您描述的方式“扩展属性”,不。

但是创建一个新类型很容易,它代表来自和两个其他值的转换。DateTime例如,和之类的类型TimeSpan都只是围绕 along处理转换为不同语义值的包装器。老实说,听起来你应该有一个新类型,因为你有一个消费者想要以一种方式处理的值,但它实际上在内存中表示为其他东西,并且类型在许多情况下都非常擅长实现这一点这超出了获取和设置属性值的范围。

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();
    }
}

类型中的基础字段可以是您想要转换的任何内容,然后您可以在一个地方定义您的转换逻辑。


推荐阅读