public interface IApiUserProvider
{
Dictionary<Guid, string> UserNamesByToken { get; }
string this[Guid token] { get; }
}
public class ApiUserProvider : IApiUserProvider
{
private readonly ICacheProvider _cacheProvider;
private readonly IEntitySet<ApiUser> _apiUsers;
private string CacheKey
{
get
{
return string.Format("{0}-{1}", GetType().Name, "ApiUsersByToken");
}
}
public ApiUserProvider(ICacheProvider cacheProvider, IEntitySet<ApiUser> apiUsers)
{
_cacheProvider = cacheProvider;
_apiUsers = apiUsers;
}
public Dictionary<Guid, string> UserNamesByToken
{
get
{
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u.Name));
}
}
public string this[Guid token]
{
get { return UserNamesByToken.GetValueOrDefault(token); }
}
}
当我更换
string this[Guid token] { get; }
ApiUser this[Guid token] { get; }
我在此代码中收到错误
return string : cannot convert to object
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u.Name));
请告诉我如何将其转换为对象类型
答案 0 :(得分:0)
首先,您必须更新字段 UserNamesByToken
public Dictionary<Guid, ApiUser> UserNamesByToken
{
get
{
return _cacheProvider.Get(CacheKey, () => _apiUsers.Where(u => u.IsActive).ToDictionary(u => u.Token, u => u));
}
}
不要忘记更新ToDictionary(u => u.Token, u => u)
然后更新 IApiUserProvider 界面
public interface IApiUserProvider
{
Dictionary<Guid, string> UserNamesByToken { get; }
ApiUser this[Guid token] { get; }
}
之后更新索引器
public string this[Guid token]
{
get { return UserNamesByToken.GetValueOrDefault(token); }
}
如果这没有帮助,请告诉我:)。