1

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!

3
  • 1
    you forget braces: new Lazy<T>(()=> InitConfig()); Commented Jun 15, 2016 at 8:59
  • Try taking away the () => ? Commented Jun 15, 2016 at 9:00
  • after I add brace() , but still have some problem.. Commented Jun 15, 2016 at 9:06

3 Answers 3

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, but I do add braces (),and I stil have some problem.
0

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

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

Comments

0

Try changing

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

to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.