Is it OK to call virtual properties from the constructor of a NHibernate entity?

前端 未结 6 603
有刺的猬
有刺的猬 2020-12-11 01:02

take a look at this example code:

public class Comment
{
    private Comment()
    { }

    public Comment(string text, DateTime creationDate, string authorE         


        
6条回答
  •  死守一世寂寞
    2020-12-11 01:18

    To expand on Paco's answer:

    In most cases it doesn't hurt. But if the class is inherited, virtual allows the properties get/set to be overriden, so the behavior is no longer fully encapsulated and controlled, so it can break, in theory. FxCop warns about this because it's a potential problem.

    The point of FxCop is to help warn you about potential problems though. It is not wrong to use properties in a constructor if you know you who/what is ever going to inherit from the class, but it isn't officially 'best practice'.

    So, the answer is that it's fine as long as you control any inheritence of the class. Otherwise, don't use it and set the field values directly. (Which means you can't use C# 3.0 automatic get/set properties--you'll have to write properties wrapping fields yourself.)

    Side note: Personally, all of my projects are web sites that we host for clients. So assuming this setup stays the same for a project, than it's worth the trade-off of having to duplicate the various null/argument checking. But, in any other case where I am not sure that we'll maintain complete control of the project and use of the class, I wouldn't take this shortcut.

提交回复
热议问题