当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Setting "this" equal to an existing object in a constructor

问题描述:

This question already has an answer here:

  • C# class contructor assigning to 'this'

    2 answers

网友答案:

You have made some architectural mistakes:

The first one is that a domain model entity must not know how it must be saved / loaded. So you've broken the Single Responsibility Principle.You must have a repository or some other pattern over them that handles persistance logic.

The second mistake is that generally speaking you've introduced a concrete dependency into your domain model entity ( the DAL class is seen as the concrete type in your domain model entity). This is bad habbit and you just violated the inversion of control principle and the general spoken "code over abstraction and not on concrete implementations" rule.

网友答案:

You can have a static GetObject instead assgin all properties in constructor.

public class MyObj{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public DateTime CreateDate { get; set; }

    public static MyObj GetObject(int prmId){
     var obj = DAL.get(prmId).FirstOrDefault();
     return obj != null ? obj : new MyObj();
    }
}


static class DAL {
     public static List<MyObj> get(int? prmId){ 
         // database stuff to call a Stored Procedure and return 0 or more MyObjs
     }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: