我们通常定义一个静态对象:
public static class Common
{
public static readonly string A = "a";
public static readonly string B = "b";
}
通过 Common.A 这样的方式就可以使用了。
但是我现在希望 Common 类支持另外一个使用方式----可以将它作为另一个类的一个属性字段:
public class Tools
{
///应当如何被定义?
public Common Common { get; set; }
}
我希望同时可以这样使用 :
public class Test
{
public void sample()
{
Tools tool = new Tools();
///可以这样用
string value = tool.Common.A;
///也可以这样用
value = Common.A;
}
}
那么在Tools对象里面,Common应该怎样被定义?
这样做的原因:Tools 是一个常用对象,用户一定知道有Tools,但不一定知道有 Common,将Common定义在Tools可以方便使用,但是 Common 确实只是一个常量集合,没必要进行 new 操作。