Нулевой анализ общих типовC#

Место общения программистов C#
Anonymous
Нулевой анализ общих типов

Сообщение Anonymous »

Я хотел бы настроить метод расширения, чтобы проверить, является ли невозможным нулевым или содержит какие -либо нулевые значения. И использовать метод в нулевом включенном коде. Например: < /p>
private static List? MyMethod()
{
var test123 = new List { "A", "B", null };
return test123;
}

private void Main()
{
var mylist = MyMethod();
if (mylist.IsOrContainsNull()) { return; }

//nullable analysis says this is safe because the enumerable does not contain any nulls.
var a = mylist.First().ToLower();
}
< /code>
Самое близкое, что я могу получить, это ниже. Есть ли в любом случае, чтобы приблизиться к вышеизложенному? < /P>
///
/// Return true if the enumerable is null or contains any nulls
///
public static bool IsOrContainsNull([NotNullWhen(false)] this IEnumerable? enumerable, [NotNullWhen(false)] out IEnumerable? enumerableOut) where T : class
{
enumerableOut = null;
if (enumerable == null) { return true; }
if (enumerable.Any(item => item == null)) { return true; }

enumerableOut = enumerable.Select(item => item!);
return false;
}

private void Main()
{
var mylist = MyMethod();
if (mylist.IsOrContainsNull(out var myList2)) { return; }

//nullable analysis says this is safe because the enumerable does not contain any nulls.
var a = myList2.First().ToLower();
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... eric-types

Вернуться в «C#»