c# - 有没有办法在 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;}
...
}
这是可能的吗?
解决方案
没有办法以您描述的方式“扩展属性”,不。
但是创建一个新类型很容易,它代表来自和两个其他值的转换。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();
}
}
类型中的基础字段可以是您想要转换的任何内容,然后您可以在一个地方定义您的转换逻辑。
推荐阅读
- mysql - MySQL如何进行查询以从我的联结表中获取信息以及不在该联结中的数据
- jmeter - 从外部配置文件中指定值
- unity3d - Unity DOTS 对普通游戏有多大好处?
- r - 在 R 中为这两个直方图添加图例
- python - for 循环过早停止而未覆盖参考列表中的所有项目
- playframework - 使用分块传输编码从 scala Play 服务器流式传输案例类对象
- sql - 是否可以即时将文本列转换为 json,然后在 postgres 中对其进行查询?
- elasticsearch - ElasticSearch:仅在满足多个条件时提升
- android - 查看 Android Studio 调试器中的所有方法调用?
- go - 供应商目录创建重复的冲突目录