YUu
YUu

Reputation: 79

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'. 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

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,

"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!

Upvotes: 1

Views: 547

Answers (3)

RB.
RB.

Reputation: 37172

You just need to change the code to either call InitConfig, or to use it as the action. 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.

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();
}

Upvotes: 2

DAXaholic
DAXaholic

Reputation: 35328

Try changing

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

to

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

Upvotes: 0

Rahul Nikate
Rahul Nikate

Reputation: 6337

InitConfig() is a function. So you need to add parentheses () for InitConfig() function.

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

Upvotes: 0

Related Questions