开发者

Adding multiple delegates to Func<T> and returning result of first lambda delegate (C#)?

开发者 https://www.devze.com 2023-03-16 18:00 出处:网络
I want to add a lambda function to a Func<T>. Furthermore I would like the returned value to be that of the first lambda delegate (I cannot initially change the order the first one will always b

I want to add a lambda function to a Func<T>. Furthermore I would like the returned value to be that of the first lambda delegate (I cannot initially change the order the first one will always be applied first). When I try to do this with the += syntax I get the following:

Error 44 Operator '+=' cannot be applied to operands of type 'System.Func<TEntity>' and 'lambda expression'

How can I achieve the above? I would really like to avoid using the traditional delegate syntax if possible.

class Transaction
{
    static Func<TEntity> ifNullInitializeWit开发者_StackOverflow中文版hThisReturnedObject = () => default(TEntity);

    public static bool IsDirty { get; private set; }

    public init (Func<TEntity> IfNullInitializeWithThisReturnedObject)
    {
         ifNullInitializeWithThisReturnedObject = IfNullInitializeWithThisReturnedObject;
    }
    public void somemethod()
    {
        ifNullInitializeWithThisReturnedObject += () => 
        { 
            IsDirty = true; 
            return default( TEntity ); 
        };
    }
}


Why not use the traditional delegate syntax, and then get the invocation list explicitly? For example:

delegate int fdelegate();

var f1 = new Func<int>(() => { return 1; });
var f2 = new Func<int>(() => { return 2; });

var f1d = new fdelegate(f1);
var f2d = new fdelegate(f2);
fdelegate f = f1d;
f += f2d;

int returnValue;
bool first = true;
foreach (var x in f.GetInvocationList())
{
    if (first)
    {
        returnValue = ((fdelegate)x)();
        first = false;
    }
    else
    {
        ((fdelegate)x)();
    }
}


+= is for events. You want a List < Func < TEntity > >. Given such a list, you could do this:

// funcList is an IEnumerable<Func<TEntity>> we got somehow
bool firstTime = true;
TEntity result;
foreach (f in funcList)
{
    if (firstTime)
        result = f();
    else
        f();
    firstTime = false;
}
return result;


It sounds like you're trying to use a lambda as a multicast delegate, which isn't what it is.

See this StackOverlflow question: Use of multicast in C# multicast delegates

I'd advise either go back to using the Delegate syntax like this: http://msdn.microsoft.com/en-us/library/ms173175(v=vs.80).aspx, or use a List<Func<TEntity>>.


What if you created a collection: List<Func<TEntity>> ?

0

精彩评论

暂无评论...
验证码 换一张
取 消