加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 标识异步方法的表达式会导致编译器警告

发布时间:2020-12-15 22:53:17 所属栏目:百科 来源:网络整理
导读:我使用表达式来标识类中的特定方法,并返回该方法的属性.当方法是异步的时,编译器会给我一个警告,即应该等待该方法. 有没有其他方法可以识别方法,或任何方式来抑制警告,而不使用pragma?我不想使用字符串来识别方法. Resharper建议使用async / await,但异步la
我使用表达式来标识类中的特定方法,并返回该方法的属性.当方法是异步的时,编译器会给我一个警告,即应该等待该方法.

有没有其他方法可以识别方法,或任何方式来抑制警告,而不使用pragma?我不想使用字符串来识别方法.

Resharper建议使用async / await,但异步lambda表达式不能转换为表达式树.

其他答案是任务的扩展方法,但后来我无法使用该属性获取方法.

示例代码:

class Program
{
    static void Main(string[] args)
    {
        var attributeProvider = new AttributeProvider();
        var attributeText = attributeProvider.GetAttribute<Program>(
            p => p.MethodA()); //Warning: Because this call is not awaited,...
    }

    [Text("text")]
    public async Task<string> MethodA()
    {
        return await Task.FromResult("");
    }
}

public class AttributeProvider
{
    public string GetAttribute<T>(Expression<Action<T>> method)
    {
        var expr =(MethodCallExpression) method.Body;

        var attribute = (TextAttribute)Attribute.GetCustomAttribute(
            expr.Method,typeof(TextAttribute));

        return attribute.Text;
    }
}

public class TextAttribute : Attribute
{
    public string Text { get; set; }

    public TextAttribute(string text)
    {
        Text = text;
    }
}

解决方法

由于它只是一个Action< T>,编译器会看到你正在调用一个Task但没有对它做任何事情.在这种情况下,这是故意的,所以你可以忽略警告.为了避免警告,您可以添加GetAttribute方法的重载以获取Func< T,object>而不是动作< T>.

public string GetAttribute<T1>(Expression<Func<T1,object>> method)

这样,编译器会看到你期望一个结果(在这种情况下是一个Task),并假设你会对它做一些事情,而不是警告你不等待它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读