开发者

Enum datatype in interface in C#

开发者 https://www.devze.com 2023-04-08 18:06 出处:网络
How to use enum datatype in interface? Is this possible? public interface IPar开发者_运维技巧ent1

How to use enum datatype in interface?

Is this possible?

public interface IPar开发者_运维技巧ent1
{
    string method1(Test enum);
}

public class Parent1 : IParent1
{
    public enum Test 
    {
        A, 
        B, 
        C
    }

    public string method1(Test enum)
    {
        return enum.ToString();
    }
}


enum is a reserved keyword in C#. You can prefix it with @ if you want to use it as variable name:

public enum Test { A, B, C };

public interface IParent1
{
    string method1(Test @enum);
}

public class Parent1 : IParent1
{
    public string method1(Test @enum)
    {
        return @enum.ToString();
    }
}

But I don't like using reserved words for variable names. A better approach would be:

public enum Test { A, B, C };

public interface IParent1
{
    string method1(Test test);
}

public class Parent1 : IParent1
{
    public string method1(Test test)
    {
        return test.ToString();
    }
}


Don't see any problem with that. But why do you nest your enum declaration in the interface implementation? Your code will not compile, because: 1. You're using reserved word enum 2. value is not declared

Try use this:

public enum Test { A, B, C };

public interface IParent1 { string method1(Test @enum);}

public class Parent1 : IParent1
{
    public string method1(Test @enum)
    {
        return @enum.ToString();
    }
}


If you want your enum to be different in each implementing class you should use a generic interface like

public interface MyInterface<T>
{
    string MyMethod(T myEnum)
}

If it should be the same for all implementing classes just don't put it outside any class:

public enum MyEnum { A, B, C }

public interface MyInterface
{
    string MyMethod(MyEnum myEnum)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消