简体   繁体   中英

Does EnumBuilder always create enum which are not CLS-Compliant ? How to make the enum CLS compliant?

Below code sample generates TempAssembly.dll with an enum Elevation in it.

 public static void Main()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            AssemblyName aName = new AssemblyName("TempAssembly");
            AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
            EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));
            eb.DefineLiteral("Low", 0);
            eb.DefineLiteral("High", 1);
            Type finished = eb.CreateType();
            ab.Save(aName.Name + ".dll");
            foreach (object o in Enum.GetValues(finished))
            {
                Console.WriteLine("{0}.{1} = {2}", finished, o, ((int)o));
            }
        }

I referenced TempAssembly.dll and used the enumeration Elevation in another project(say project TestA). As I want the code to be CLS-Compliant I added the following attribute to the project TestA.

[assembly:System.CLSCompliant(true)]

The code where I am getting warning is:

public class TestClass
{
    public Elevation Elev { get; set; } 
}

The warning

Warning 1 Type of 'TestA.TestClass.Elev' is not CLS-compliant

I checked documentation on how to write CLS Compliant code but I am unable to do much as the enum is being created dynamically. Any suggestions , how can I make the enum CLS compliant?

Have you tried marking the assembly as CLS-compliant?

ab.SetCustomAttribute(new CustomAttributeBuilder(
        typeof(CLSCompliantAttribute).GetConstructor(new[] { typeof(bool) }),
        new object[] { true }));

You should be able to do the same on eb too:

eb.SetCustomAttribute(new CustomAttributeBuilder(
        typeof(CLSCompliantAttribute).GetConstructor(new[] { typeof(bool) }),
        new object[] { true }));

When you apply the CLSCompliantAttribute to you TestA assembly you also need to add the CLSCompliantAttribute to your dynamically created TempAssembly. Since the attribute is not defined on it, it is by default not CLS Compliant .

See also MSDN for more information:

If no CLSCompliantAttribute is applied to a program element, then by default:

  • The assembly is not CLS-compliant.
  • The type is CLS-compliant only if its enclosing type or assembly is CLS-compliant.
  • The member of a type is CLS-compliant only if the type is CLS-compliant.

So you have two options. Remove the CLSCompliantAttribute from your TestA assembly or add the CLSCompliantAttribute to your TempAssembly.

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