具有特定属性的类的扩展

时间:2016-06-03 16:02:03

标签: c# attributes

我想为任何具有特定属性的类提供扩展方法。

为了澄清,我必须自己进行对象的序列化。但我想只序列化具有此自定义属性的对象。 我知道我可以通过从另一个基类继承来实现它,但我已经拥有了class属性,我认为它会更优雅,所以你总能看到一个对象是否可以自定义序列化。

类似的东西:

>>> x = numpy.array([1.5, 2.3, 5])
>>> x//1
array([ 1.,  2.,  5.])
>>> floor(x)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    floor(x)
TypeError: only length-1 arrays can be converted to Python scalars

2 个答案:

答案 0 :(得分:4)

属性用于存储元数据 - 静态和const的值,在编译时是已知的。他们无法向您的类添加方法/字段 - 接口就是这样做的。你可以做的是创建一个界面:

public interface ICustomSerializable{
    string CustomSerialize();
}

另一个选择是将类与序列化逻辑分开。序列化将由另一个类处理。例如:

public class CustomSerializer{

   public string CustomSerialize(object myObject){
       // for example if object has no CustomAttribut attribute 
       // you can throw "not serializable" exception here.

   }
}

答案 1 :(得分:0)

你不能用普通的.NET做到这一点。它被称为AOP或Aspect Oriented Programming

有一些第三方提供商,例如PostSharp提供这些选项。