jeudi 27 avril 2017

How to get the value of a Custom Attribute method parameter in C# [duplicate]

This question already has an answer here:

I'm using custom attributes in C#. I can't figure out how to get the value of a method parameter with a custom attribute applied to it.

I call my method like this:

carProcessor(4, "V8");

My method signature looks like:

[CarTypeAttribute("Pontiac")]
public void carProcessor(int doorCount, [CarParamAttribute("EngineType")] string engine)
{
    process();
}

I retrieve it's values via reflection from in the process method:

public void process()
{
    MethodBase method = new StackFrame(1).GetMethod();
    var attributes = method.GetCustomAttributes(true);

    foreach(Attribute attr in attributes){
        Type attrType = attr.GetType();

        if(attrType == typeof(CarTypeAttribute)){
            CarTypeAttribute carAttr = (CarTypeAttribute)attr;
            Console.WriteLine("Found CarTypeAttribute!");
            Console.WriteLine("value" + carAttr.Value);
        }
    }
    //Above works perfect and finds CarTypeAttribute and the value Pontiac

    //Lets get the method parameter attribute
    ParameterInfo[] parameterInfos = method.GetParameters();
    if (parameterInfos.Length > 0)
    {
        for(int j = 0; j < parameterInfos.Length; j++)
        {
            Object[] paramAttributes = parameterInfos[j].GetCustomAttributes(typeof(CarParamAttribute), false);

            if (paramAttributes.Length > 0)
            {
                Console.WriteLine("Parameter " + parameterInfos[j].Position + ", name = " + parameterInfos[j].Name + " has attributes: ");
                //above prints: Parameter 2, name = engine has attributes:
                for(int k = 0; k < paramAttributes.Length; k++)
                {
                    Console.WriteLine("Found it: " + paramAttributes[k]); 
                    //above prints: Found it: CarParamAttribute

                }
                Console.WriteLine("The value for this method parameter is " + ???????); 
                //want above to print that V8 was passed, but don't know how
            }
        }
    }

}

So, I can successfully see that the method has a CarTypeAttribute and that it's value is set to Pontiac. Also I can see that it has a parameter with the CarParamAttribute and it's value is set to EngineType, but I don't know the value of the string parameter passed to the function associated with the CarParamAttribute, which in this case was V8. How do I get that value? If you can't get that, I don't see what the point of being able to apply custom attributes to method parameters is?

Thanks





Aucun commentaire:

Enregistrer un commentaire