c# - C# 中的类和方法,这是一个好方法吗?

标签 c# asp.net class methods

我试图在我的 asp.net web 应用程序中构建一个与数据库交互的类。我需要你对如何设计它的意见,这是我想到的一个例子

public class Person
{
    int personId;
    string name;
    string lastName;

    public int PersonId
    {
        get { return personId; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public Person()
    {

    }

    public static void Save(Person p)
    {
        //datalayer here
        //save the person class
    }

    public static Person GetPerson(int person_id)
    {
        //datalayer here
        //get the person from database and return a person class
        Person p = new Person();
        p.personId = 10;
        p.name = "Alex";
        return p;
    }
}

这样我就可以使用数据库方法而不必实例化类:

Person p = Person.GetPerson(19);
p.Name = "Alex...";
Person.Save(p);

感谢您的帮助。

最佳答案

使用 Automatic 属性,因为您的私有(private)字段在您的代码中具有相同的作用。

我认为,Save 是一个Operation,可以在Person Entity 的对象上完成。所以我不会将其保留为静态方法。我会将您的 Save 代码作为 Person 对象的方法移动。所以我会像 obj.Save() 那样调用它。要加载数据,我会使用类 constructor 的重载版本。

public class Person
{
    int personId;      

    public int PersonId
    {
        get { return personId; }
    }    
    public string Name { set;get;}   
    public string LastName { set;get;}        

    public Person() {}

    public Person(int person_id)
    {
        //call to datalayer here
        //get the person from database and return a person class          
        personId = 10;
        Name= "Alex";  // set the public property value here           
    }
    public bool Save()
    {
        //datalayer here
        //save the person class and return
      // true/false /or new ID (change return type)
    }    

}

调用时,

Person p = new Person(19);  //get existing person
p.Name = "New Name";
p.Save();

编辑:另一种(更好的)方法是让您的实体类保持简单的 POCO。这意味着那里没有数据访问/BL 代码。它看起来就像

public class Person
{
  public int ID { set;get;}
  public string Name { set;get;}
}

并且有一个Repository 为您做数据操作。所以你的存储库可能有这样的方法

public interface IRepository
{ 
   Person GetPerson(int id);
   bool SavePerson(Person person);
}

您可以在类中实现此接口(interface)以执行您的数据访问操作

public class Repository:IRepository
{
  //implementation of your DA methods here
}

现在你可以像这样从不同的层(业务层)调用它

IRepository repo = new Repository();

var person=repo.GetPerson(19);  
person.Name="Updated Name";
repo.Save(person);

关于c# - C# 中的类和方法,这是一个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11584190/

相关文章:

c# - EF5 和分离的 POCO,导航属性返回 null

asp.net - Web 矩阵网页的查看引擎

asp.net - 文件一键上传和显示

c++ - 定义子类的对象

javascript - 第二个参数 Object.create

c# - 模型检查工具c#

C# 循环窗口窗体元素

c# - 使用 C# 和 Compact Framework 管理无线网络连接

c# - 自定义 WebAPI "Access Denied"响应

c++ - 错误 C2679 : binary '+' : no operator found which takes a right-hand operand of type