具有虚拟属性的部分类?

时间:2013-02-12 13:45:16

标签: c# partial-classes

是否可以在分部类中拥有虚拟属性?在我的场景中,我们有自动生成的类,我们的Micro-ORM使用它们并完全映射到我们的数据库表。

我们经常希望扩展这些类,因此在这种情况下使用partial关键字绝对没问题。

但我有一种情况,我希望在部分类中覆盖自动生成的getter。

例如:

public partial class MyClass {
   public int MyProperty{ get; set; }
}

..我想覆盖get并实现一些自定义逻辑,不用操纵自动生成的代码。这很重要。

感谢。

1 个答案:

答案 0 :(得分:0)

也许你可以修改自动生成的类来将gets和sets放在其他文件中。 例如:

// file: MyClass_1.cs
public partial class MyClass
{
   public int MyProperty
   {
      get { this.MyPropertyGet(); }
      set { this.MyPropertySet(value); }
   }
}

在其他文件中:

// file: MyClass_2.cs
public partial class MyClass
{
   private int _myProperty;

   private int MyPropertyGet()
   {
      return _myProperty;
   }

   private void MyPropertySet(int value)
   {
      _myProperty = value;
   }
}