apacay
apacay

Reputation: 1712

Abstract, Delegates and Metaprogramming c# headache

I have an abstract class as a Matrix of strategies (Strategy Pattern) to replace certain variables from a MailMessage.

The thing is this won't work because Compiler says KC Does exist in that context. (And asks the maybe I'm missing an assembly stuff)

  public abstract class MailVariables
    {
        public abstract string IdReference { get; set; }
        public abstract void DoReplace(ref String subject, ref String body, MailAddressCollection to, MailAddressCollection cc, MailAddressCollection bcc);

        protected virtual void OnMatchDo(ref String Text, List<KeyCriteria> List)
        {
            String auxText = Text;
            List.ForEach(KC =>
            {
                if (auxText.Contains(KC.Key))
                {
                    KC.ReplaceCriteria criteria; // <-- Here says KC does not exist
                    auxText.Replace(KC.Key, criteria(KC.Key));
                }
            });
            Text = auxText;
        }

    }

    protected class KeyCriteria
    {
        public string Key;
        public delegate string ReplaceCriteria(string parameter);
    }

@EDIT: Forgot to say what was my actual question, sry

Is there a viable way to put it?

Is there a neater way to put it once this works?

Upvotes: 0

Views: 87

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273691

In KC.ReplaceCriteria criteria; , KC is a variable. That it is a lambda param does not matter.

What you need is a type, like:

    if (auxText.Contains(KC.Key))
    {
        <maybe-some-namespace>.ReplaceCriteria criteria;         // declare a var
        criteria = new <maybe-some-namespace>.ReplaceCriteria(); // make an instance 
        auxText.Replace(KC.Key, criteria(KC.Key));               // use it
    }

That does not make a lot of sense yet but at least it's valid C#

Edit:

on a second read, I think it's just :

    if (auxText.Contains(KC.Key))
    {                        
        auxText.Replace(KC.Key, KC.criteria(KC.Key));    
    }

Upvotes: 2

Related Questions