如果直接在C#中调用方法,如何显示警告

问题描述

{
    public class MyClass
    {
        // all the call to GetData() of apiHelper should pass through this method
        public async Task<T> InitiateAPICallAsync<T>(Task<T> apiCall) where T : BaseResponse
        {
            var response = await apiCall;
            // some common code work using response data
            return response;
        }

        public async void MyFunc()
        {
            var helper = new APIHelper("1","2");
            //
            var response1 = await InitiateAPICallAsync(helper.GetData<Response1>()); // correct way
            var rewponse2 = await helper.GetData<Response1>(); // incorrect way,need to show warning
        }
    }


    public class APIHelper
    {
        public APIHelper(string a,string b)
        {
            // some code
        }

        public async Task<T> GetData<T>()
        {
            await Task.Delay(1000); // network call
            // other code
            return default;
        }
    }

    public class Response1 : BaseResponse { }

    public class Response2 : BaseResponse { }

    public class BaseResponse { }
}

在我的应用程序MyClass中,有一个名为InitiateAPICallAsync()的方法。对GetData()的{​​{1}}方法的所有调用都必须通过此方法。如果直接调用APIHelper方法而不通过GetAsync(),则需要显示警告。

注意:这是一个示例代码段,在我的实时项目中,InitiateAPICallAsync代表一个连接库。 APIHelper代表另一个名为service的库。

解决方法

如果直接在c#中调用方法,如何显示警告?

使用CallerMemberName属性是以下解决方案的核心,感谢Fumeaux的评论,我尝试将CallerMemberName属性直接放在GetData方法上方以获取调用者,但结果是{ {1}},而不是MyFunc。因此,我尝试使用InitiateAPICallAsync作为delegate参数,以确保InitiateAPICallAsync将调用GetData。以下代码已简化。

InitiateAPICallAsync

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...