简体   繁体   中英

What does this syntax mean in c#?

I may not have it correct, but I saw something like this above a WebMethod:

[return:(XmlElement("Class2"),IsNullable = false)]
public Class2 MEthod1()
{

}

I saw a vb version first and I used a converter to convert it to c#. I have never seen it before. It's in a vb 6 asmx file.

It's an attribute target, and it's being used in your example to disambiguate usage on the return value from other elements:

// default: applies to method
[SomeAttr]
int Method1() { return 0; } 

// applies to method
[method: SomeAttr]
int Method2() { return 0; } 

// applies to return value
[return: SomeAttr]
int Method3() { return 0; } 

When creating attributes you can specify which language elements an attribute can be applied to. This is illustrated in the example below.

For a list of available targets see here:
http://msdn.microsoft.com/en-us/library/system.attributetargets.aspx

namespace AttTargsCS 
{
    // This attribute is only valid on a class.
    [AttributeUsage(AttributeTargets.Class)]
    public class ClassTargetAttribute : Attribute {
    }

    // This attribute is only valid on a method.
    [AttributeUsage(AttributeTargets.Method)]
    public class MethodTargetAttribute : Attribute {
    }

    // This attribute is only valid on a constructor.
    [AttributeUsage(AttributeTargets.Constructor)]
    public class ConstructorTargetAttribute : Attribute {
    }

    // This attribute is only valid on a field.
    [AttributeUsage(AttributeTargets.Field)]
    public class FieldTargetAttribute : Attribute {
    }

    // This attribute is valid on a class or a method.
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
    public class ClassMethodTargetAttribute : Attribute {
    }

    // This attribute is valid on any target.
    [AttributeUsage(AttributeTargets.All)]
    public class AllTargetsAttribute : Attribute {
    }

    [ClassTarget]
    [ClassMethodTarget]
    [AllTargets]
    public class TestClassAttribute {
        [ConstructorTarget]
        [AllTargets]
        TestClassAttribute() {
        }

        [MethodTarget]
        [ClassMethodTarget]
        [AllTargets]
        public void Method1() {
        }

        [FieldTarget]
        [AllTargets]
        public int myInt;

        static void Main(string[] args) {
        }
    }
}

It's an attribute modifying how the return value of the method is serialized into XML.

In general, the [return: Attribute] syntax is used to indicate that the attribute applies to the return value of a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM