У меня есть метод делегата (фонд , определенный с выражением Lambda), в которой используется переменная, выходящая извне его контекста. Обнаруйте его и посылает мне предупреждение: «Наблюдение за возможной нулевой ссылкой». Каковы лучшие практики в этом случае?public void Method()
{
//This var is never supposed to be null,
//but if I don't use null here, I get "use of unassigned variable" error
ObjType someObj = null;
//Declaring the delegate function
Func function = () =>
{
//get a warning here for using a possibly null variable
//I'd like to avoid using the null forgiving operator here (!)
return someObj.DoSomething();
};
//usage
while(...someCondition...)
{
//here, before using the delegate, I guarantee that someObj is not null
someObj = GetObj(...getObjectOptions...);
//here I use the delegate - FunctionUserClass is not mine to change it,
//so I do need to use a Func
if (FunctionUserClass.UseFunction(function))
//... work on 'someCondition'
//... work on 'getObjectOptions'
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -forgiving
Почтение возможной нулевой ссылки внутри делегата - избегайте нулевого оператора ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Преобразование нулевого буквального или возможного нулевого значения в не нулевой тип
Anonymous » » в форуме C# - 0 Ответы
- 13 Просмотры
-
Последнее сообщение Anonymous
-