以下是MSDN在何时使用静态类时要说的内容:
Run Code Online (Sandbox Code Playgroud)static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... }使用静态类作为与特定对象无关的方法的组织单位.此外,静态类可以使您的实现更简单,更快,因为您不必创建对象来调用其方法.以有意义的方式组织类中的方法很有用,例如System命名空间中Math类的方法.
对我来说,这个例子似乎并没有涵盖静态类的很多可能的使用场景.在过去,我已经将静态类用于相关函数的无状态套件,但这就是它.那么,在什么情况下应该(而且不应该)将一个类声明为静态?
我在ASP.NET应用程序(使用Entity Framework)中使用MVC模式的方式如下:
1)我的Models文件夹包含所有EF实体以及我的ViewModel
2)我有一个Helpers文件夹,我存储为特定应用程序创建的类.
3)在我的Helpers文件夹中,我有一个名为的静态类MyHelper,其中包含使用EF访问数据库的方法.
namespace myApp.Helpers
{
public static class MyHelper
{
public static async Task<ProductVM> GetProductAsync(int productId)
{
using (var context = new myEntities())
{
return await context.vwxProducts.Where(x => x.ProductId == productId).Select(x => new ProductVM { A = x.A, B = x.B }).FirstOrDefaultAsync();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
4)我的控制器然后在必要时调用这些函数:
namespace myApp.Controllers
{
public class ProductController : Controller
{
[HttpGet]
public async Task<ActionResult> Index(int productId)
{
var productVM = await MyHelper.GetProductAsync(productId);
return …Run Code Online (Sandbox Code Playgroud) 从概念上讲,当方法只接受输入并将输入重新格式化为输出时,使用静态方法(C#)是否合适?例如:
public static string FormatString(string inputString){
return "some formatting" + inputString + "Some other formatting";
}
Run Code Online (Sandbox Code Playgroud)
如果我有一些这样的方法,静态"实用"类是一个好主意吗?