What does this syntax mean in C #?

Maybe I have it wrong, but I saw something like WebMethod:

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

At first I saw a version of vb, and I used a converter to convert it to C #. I've never seen this before. This is in the asmx vb 6 file.

+6
source share
2 answers

This is the purpose of the attribute, and it is used in your example to disambiguate the use of 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 the attribute can apply to. This is shown in the example below.

For a list of available goals, 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) { } } } 
+16
source

This is an attribute that changes how the return value of a method is serialized in XML.

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

+5
source

Source: https://habr.com/ru/post/895462/


All Articles