[英]c# - How to implement a non generic interface in a generic class with constraints
[英]C# generic class implement error
实现C#泛型类以重构类,我面临这样的问题:C#泛型类实现错误错误CS0428无法将方法组'InitConfig'转换为非委托类型'T'。 您是否打算调用该方法?
错误CS1662无法将lambda表达式转换为预期的委托类型,因为该块中的某些返回类型不能隐式转换为委托返回类型
public class RedisDatabaseService<T> : IRedisDatabase<T> where T : class,IConfig
{
public Lazy<T> lazyConfig { get; } = new Lazy<T>(()=> InitConfig);
public T InitConfig()
{
throw new NotImplementedException();
}
}
public interface IRedisDatabase<T> where T : class
{
T InitConfig();
}
在添加brace()之后,但是仍然存在一些问题,
“无法访问非静态方法...” ,因此我无法实现所有接口成员。.如何修改代码以避免错误? 非常感谢!
您只需要更改代码以调用InitConfig
或将其用作操作即可。 请注意,我更喜欢第二个,因为它更有趣。
或者:
new Lazy<T>(()=> InitConfig());
要么
new Lazy<T>(InitConfig);
这是我编译的代码。 请注意,我在构造函数中进行赋值(因为我仍在使用Linqpad 4!)-我认为这将解决您的错误。
public class RedisDatabaseService<T> : IRedisDatabase<T> where T : class, IConfig
{
public RedisDatabaseService()
{
// Move your lazy assignment to the constructor, as so:
lazyConfig = new Lazy<T>(InitConfig);
}
public Lazy<T> lazyConfig { get; private set; }
public T InitConfig()
{
throw new NotImplementedException();
}
}
public interface IRedisDatabase<T> where T : class
{
T InitConfig();
}
InitConfig()
是一个函数。 因此,您需要为InitConfig()
函数添加parentheses ()
。
public Lazy<T> lazyConfig { get; } = new Lazy<T>(()=> InitConfig());
尝试改变
new Lazy<T>(() => InitConfig);
至
new Lazy<T>(() => InitConfig());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.