我想编写一个C类,使其具有一个静态字段,该字段初始化一次并且对于所有C<>保持不变。
这可能吗?
以下是我正在使用的示例:
void Main()
{
Console.WriteLine (C<A>.Value);
Console.WriteLine (C<B>.Value);
Console.WriteLine (C<A>.Value2);
Console.WriteLine (C<B>.Value2);
}
class C<T>
{
static O O = new O();
public static string Value { get { return "value of C<T> where T : " + typeof(T).Name; } }
public static string Value2 { get { return O.ToString() ?? "value of C<T> where T : " + typeof(T).Name; } }
}
class O
{
Guid guid;
public O()
{
this.guid = Guid.NewGuid();
Console.WriteLine ("O created {0}", this.guid);
}
public override string ToString()
{
return this.guid.ToString();
}
}
class A
{
}
class B
{
}
输出:
value of C<T> where T : A
value of C<T> where T : B
O created 05e6885b-2aa3-4d0d-aec1-fefbe5294f07
05e6885b-2aa3-4d0d-aec1-fefbe5294f07
O created 864554bf-6980-4a0f-9b63-4c0affa21222
864554bf-6980-4a0f-9b63-4c0affa21222
答案 0 :(得分:5)
当然,从BaseC派生C并在那里声明静态字段,如下所示:
class BaseC
{
protected static O = new O();
}
class C<T>: BaseC ...