【问题标题】:Have I good sense of static method我对静态方法有很好的了解吗
【发布时间】:2026-01-10 00:20:06
【问题描述】:

我的 Country 类包含 Cities 集合。

在客户端我使用 webmethod

[WebMethod]
public void AddCity(string countryCode,string name)
{
MyFacade.AddCity(countryCode,name);
}

在 Facade 我有方法

public void AddCity(string countryCode,string name)
{
Country.AddCity(countryCode,name); <-in this method is simple sql operation
}

我的问题的核心:

public class Country
{
public static void AddCity(string countryCode, string cityName)
{
//insert into table cities new city
}
}

没事吧?或者我必须创建objectCountry,并且有非静态方法AddCity?

还有一个问题:

更好的使用:

City[] cities=  Country.GetAllCities(countryCode)

City[] cities=  new Country(countryCode).GetAllCities()

【问题讨论】:

    标签: c# oop static


    【解决方案1】:

    接受countryCodecityName 作为参数对于数据访问层来说很好,但我没有看到任何应该是静态的方法。

    AddCity应该是DataConnection之类的非静态成员,这样就可以在不改变调用接口的情况下轻松mock、替换数据库等。

    【讨论】:

    • 我认为MyFacade.AddCityCountry.AddCity 都是静态的。
    • 是的,Facade 是一个静态类,而 MyFacade.both MyFacade.AddCity 和 Country.AddCity 都是静态的。
    • 这就是我不同意的。需要有状态和多态的不是Country 类型,而是数据库连接。
    【解决方案2】:

    您希望能够使用模拟框架对代码进行单元测试吗?

    基于 Ben 的回答,将 Facade 替换为接口:

    [WebMethod]
    public void AddCity(string countryCode, string name)
    {
        ICountryDataAccess dao = GetDAOFromDI(); // basically get a DI framework to manage this object instance.
        dao.AddCity(countryCode, name);
    }
    
    public interface ICountryDataAccess 
    {
        void AddCity(string countryCode, string name);
        ICollection<City> GetAllCities(string countryCode);
        // OR !
        Country Retrieve(string countryCode);
        // using an ORM or something Country then as a list of cities
    }
    
    public Country 
    {
        public virtual string CountryCode {get;set;} 
        public virtual ICollection<City> Cities {get; protected set;}
    }
    

    【讨论】:

      最近更新 更多