简体   繁体   English

C#通用类实现错误

[英]C# generic class implement error

Implement C# generic class to refactor classes,and I face the problem like this: C# generic class implement error Error CS0428 Cannot convert method group 'InitConfig' to non-delegate type 'T'. 实现C#泛型类以重构类,我面临这样的问题:C#泛型类实现错误错误CS0428无法将方法组'InitConfig'转换为非委托类型'T'。 Did you intend to invoke the method? 您是否打算调用该方法?

Error CS1662 Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type 错误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();
}

after I add brace() , but still have some problem, 在添加brace()之后,但是仍然存在一些问题,

"Cannot access non-static method..." ,so I can not implement all interface members.. How to modify the code to avoid the errors? “无法访问非静态方法...” ,因此我无法实现所有接口成员。.如何修改代码以避免错误? Thanks a lot! 非常感谢!

You just need to change the code to either call InitConfig , or to use it as the action. 您只需要更改代码以调用InitConfig或将其用作操作即可。 Note that I prefer the second as it's terser. 请注意,我更喜欢第二个,因为它更有趣。

Either: 或者:

new Lazy<T>(()=>  InitConfig());

Or 要么

new Lazy<T>(InitConfig);

This is the code I compiled with. 这是我编译的代码。 Note that I do the assignment in the constructor (as I am still using Linqpad 4!) - I think this will fix your error. 请注意,我在构造函数中进行赋值(因为我仍在使用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() is a function. InitConfig()是一个函数。 So you need to add parentheses () for InitConfig() function. 因此,您需要为InitConfig()函数添加parentheses ()

public Lazy<T> lazyConfig { get; } =  new Lazy<T>(()=>  InitConfig());

Try changing 尝试改变

new Lazy<T>(() => InitConfig);

to

new Lazy<T>(() => InitConfig());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM