在 C# 接口和接口的方法签名之一中实现枚举
我有一个接口
接口:
interface IThing
{
Enum MyEnum {get;set;}
string DoAction(MyEnum enumOptionChosen, string valueToPassIn);
}
具体实现:
public class Thing : IThing
{
public enum MyEnum
{
FirstOption,
SecondOption,
ThirdOption
}
string doAction(MyEnum enumOptionChosen, string valueToPassIn)
{
switch(enumOptionChosen)
{
case MyEnum.FirstOption:
x();
break;
case MyEnum.SecondOption:
y();
break;
case MyEnum.ThirdOption:
z();
break;
}
}
}
当我尝试编译它时,我得到“IThing.MyEnum”是一个“属性”,但像“类型”一样使用。 我缺少一些关于能够要求在 DoAction() 签名中使用 Enum 的信息。
感谢您的任何帮助。
I have an interface
Interface:
interface IThing
{
Enum MyEnum {get;set;}
string DoAction(MyEnum enumOptionChosen, string valueToPassIn);
}
Concrete implementation:
public class Thing : IThing
{
public enum MyEnum
{
FirstOption,
SecondOption,
ThirdOption
}
string doAction(MyEnum enumOptionChosen, string valueToPassIn)
{
switch(enumOptionChosen)
{
case MyEnum.FirstOption:
x();
break;
case MyEnum.SecondOption:
y();
break;
case MyEnum.ThirdOption:
z();
break;
}
}
}
When I try compiling this I get 'IThing.MyEnum' is a 'property' but is used like a 'type.'
I'm missing something about being able to require use of the Enum in the DoAction() signature.
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的接口中,
MyEnum
是变量的名称而不是类型,因此编译器不会识别它。您应该能够使用泛型来完成此任务。然后你可以像这样实现它:
In your interface
MyEnum
is the name of the variable not the type, so it won't be recognized by the compiler. You should be able to use Generics to get this done.Then you could implement it like this:
首先,在接口/具体之外声明您的枚举。
然后在你的界面中:
然后在你的类中:
你的主要问题是你试图从你的界面声明“Enum”的返回类型,而你应该声明“MyEnum”的返回类型。
请记住,枚举是一种类型。您不能强制类实现“类型”,只能实现属性/方法。
话虽这么说,我正在挠头试图弄清楚你想做什么。
Firstly, declare your enum outside of the interface/concrete.
Then in your interface:
Then in your class:
Your main problem was you were trying to declare a return type of "Enum" from your interface, when you should be declaring a return type of "MyEnum".
Remember, enum is a type. You can't force a class to implement a "type", only properties/methods.
That being said, i'm scratching my head to try and figure out what you are trying to do.
我意识到原来的帖子很旧了,但这是另一种清晰且效果良好的方法。由于枚举是公共的,因此只需在具体类和接口之外定义它即可。 (我冒昧地将枚举类型重命名为 TheEnum,以避免与属性 MyEnum 混淆。)
然后在接口和具体类中引用它。
I realize the original post is very old, but this is another approach that is clear and works well. Since the Enum is public, just go ahead and define it outside of the concrete class and the interface. (I've taken the liberty of renaming the enum type to TheEnum to avoid confusion with the property MyEnum.)
Then reference it in your interface and concrete class.