【发布时间】:2011-02-07 11:15:11
【问题描述】:
我在 C# 中有一个带有公共方法的 A 类。我想只允许 B 类访问此方法。这可能吗?
更新:
这就是我想做的:
public class Category
{
public int NumberOfInactiveProducts {get;}
public IList<Product> Products {get;set;}
public void ProcessInactiveProduct()
{
// do things...
NumberOfInactiveProducts++;
}
}
public class Product
{
public bool Inactive {get;}
public Category Category {get;set;}
public void SetInactive()
{
this.Inactive= true;
Category.ProcessInactiveProduct();
}
}
我希望其他程序员这样做:
var prod = Repository.Get<Product>(id);
prod.SetInactive();
我想确保他们不会手动调用 ProcessInactiveProduct:
var prod = Repository.Get<Product>(id);
prod.SetInactive();
prod.Category.ProcessInactiveProduct();
我想只允许 Category.ProcessInactiveProduct 访问类 Product。其他类不应调用 Category.ProcessInactiveProduct。
【问题讨论】:
-
+1 非常有趣的问题。
-
如果您只想让 B 类访问它 - 那么这不是“公共”方法。