如何解决如果直接在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。