[英]How to return instance of concrete class from method with generic return type
我有一个从我的应用程序中调用的方法。 方法是从Google.Apis.Util.Store.IDataStore
实现的。 我想从该方法返回令牌,但我不知道如何。 Token 是类类型 TokenResponse。 如何从这样的方法返回类 TokenResponse?
public Task<T> GetAsync<T>(string key)
{
//TokenResponse token = new TokenResponse();
//token.RefreshToken = @"rere545454545";
//return token; -- I would like to return this, but it throws error
return Task.FromResult<T>(default); //that works, but not much help out of it
}
更新
基本上我想返回我自己的令牌,我已经在数据库中了。 但是尝试创建一个新实例,例如:
TokenResponse token = new TokenResponse()
抛出和错误
无法创建变量类型 TokenResponse 的实例,因为它没有 new() 约束
解决问题的最简单方法是使用下一种方法:
public Task<T> GetAsync<T>(string key)
{
TokenResponse t = new TokenResponse();
// ...
return Task.FromResult((T) ((object) t));
}
您应该保证始终使用类型参数T = TokenResponse
调用方法GetAsync<T>
。 否则,此代码将抛出InvalidCastException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.