Cannot convert lambda expression to type 'object' because it is not a delegate type

前端 未结 5 1091
广开言路
广开言路 2020-12-18 17:25

I have a base class that has a bool property which looks like this:

public abstract class MyBaseClass
{
     public bool InProgress { get; protected set; }
}         


        
相关标签:
5条回答
  • 2020-12-18 18:07

    I got this error when I was missing

    using System.Data.Entity;
    
    0 讨论(0)
  • 2020-12-18 18:09

    I ran into this problem while writing unit tests. I was attempting to mock the behavior of a database to return a new object from a repository instead of actually connecting to a database.

    Make sure your object has a usable constructor. You may not be able to successfully instantiate that object the way you want to. Ensure if you using a lambda to point to a constructor that the constructor can be called in the same way in a normal instantiation statement.

    i.e.

    return x => new FakeObject();
    

    say in the case of

    var fake = new FakeObject();
    

    would not work then the lambda will also fail so be careful.

    0 讨论(0)
  • 2020-12-18 18:15

    Best would be to have the dictionary strongly typed, but if you assign the lambda to a specific lambda (delegate) first, it should work (because the compiler then knows the delegate format):

    Action<bool> inp = InProgress => base.InProgress = InProgress;
    dict.Add("InProgress", inp);
    

    Or by casting it directly, same effect

    dict.Add("InProgress", (Action<bool>)(InProgress => base.InProgress = InProgress));
    

    Of course having such a dictionary format as object is discussable, since you'll have to know the delegate format to be able to use it.

    0 讨论(0)
  • 2020-12-18 18:15

    Although the solution by @Me.Name is completely valid by itself, there's an additional trick that may come in handy in some situations (it certainly did for me): if you're converting multiple lambdas using this technique, you can factor the cast as a helper method, along the lines of

    object myDelegateToObject ( Action<bool> action ) {
        return action; // autocast to `object` superclass, no explicit cast needed
    }
    

    and then call it by simply

    dict.Add("InProgress", myDelegateToObject(InProgress => base.InProgress = InProgress));
    

    It may save you time later on - if you decide to change to change the signatures, you will have to do so in one place only.

    0 讨论(0)
  • 2020-12-18 18:24

    If you encounter this error in nopcommerce you need to add import line using System.Linq;

    0 讨论(0)
提交回复
热议问题