Почему нельзя создать константу типа T в обобщении по T (ошибка CS1959)?
Почему нельзя создать константу B
в примере ниже, ведь её тип ссылочный?
class SomeClass { }
static class Consts<T> where T : class
{
public const SomeClass A = null;
// Error CS1959
// 'Consts<T>.B' is of type 'T'.
// The type specified in a constant declaration must be sbyte, byte, short, ushort,
// int, uint, long, ulong, char, float, double, decimal, bool,
// string, an enum-type, or a reference-type.
public const T B = null;
// Менее эффективно чем константа.
public static readonly T C = null;
static void Foo()
{
SomeClass s1 = Consts<SomeClass>.A;
SomeClass s2 = Consts<SomeClass>.B;
SomeClass s3 = Consts<SomeClass>.C;
}
}
Использовались:
.NET Framework 4.8
C# 7.3