Как int? и int, Гид? и Гид, DateOnly? и DateOnly и так далее.
Тип, допускающий значение NULL, должен быть в свойстве класса, а тип, допускающий значение NULL, должен быть в ключе словаря класса. Для поиска в этом словаре следует использовать значение nullable.
Пример:
Код: Выделить всё
var t = new GenericTest # ERROR: The type 'int?' must be convertible to 'int' in order to use it as parameter 'TK' in the generic class 'GenericTest'
{
Key = null
};
t.Values.Add(1, 2);
Console.WriteLine(t.FindValue());
class GenericTest
where TK: TV
where TV : notnull
{
public TK? Key { get; set; }
public Dictionary Values { get; set; } = new();
public int FindValue()
{
if (Key == null)
return 0;
return Values.GetValueOrDefault(Key, 0);
}
}
Код: Выделить всё
var t = new GenericTest
{
Key = null
};
t.Values.Add(1, 3);
Console.WriteLine(t.FindValue());
class GenericTest
{
public TK? Key { get; set; }
public Dictionary Values { get; set; } = new(); # WARNING: Nullability of type argument 'TK' must match 'notnull' constraint in order to use it as parameter 'TKey'
public int FindValue()
{
if (Key == null)
return 0;
return Values.GetValueOrDefault(Key, 0);
}
}
Код: Выделить всё
var t = new GenericTest # WARNING: Nullability of type argument 'int?' must match 'notnull' constraint in order to use it as parameter 'TK'
{
Key = null
};
t.Values.Add(1, 3);
Console.WriteLine(t.FindValue());
class GenericTest where TK : notnull # ADDED HERE
{
public TK? Key { get; set; }
public Dictionary Values { get; set; } = new();
public int FindValue()
{
if (Key == null)
return 0;
return Values.GetValueOrDefault(Key, 0);
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... n-the-gene