C#如何在类中使用get,set和use enums [英] C# How to use get, set and use enums in a class

查看:210
本文介绍了C#如何在类中使用get,set和use enums的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我使用类存储设置。我需要它来使用set和get函数来更改和存储设置。我试过这个,但我没有让它发挥作用。任何人都可以帮我这个吗?

I have a program where I use a class store settings. I need it to use set and get functions to change and store settings. I have tried this, and I don't get it to work. Can anyone help me with this one?

    private enum _Difficulty { Easy, Normal, Hard };

    public void SetDifficulty(Difficulty)
    {
        _Difficulty = Difficulty;
    }

    public enum GetDifficulty()
    {
        return _Difficulty;
    }

无法使用枚举在一个获取设置的课程中?

Is there no way to use enums in a class with get and set?

我还需要 bool int

推荐答案

这里有几个问题:


  • 你的枚举是私有的,但是你的方法是公开的。因此,您不能使您的方法返回类型为枚举类型,或具有该类型的参数

  • 您的 SetDifficulty 方法有一个参数只是难度 - 这是参数名称还是类型?

  • 你的 SetDifficulty 方法正在尝试设置类型而不是字段

  • 您的 GetDifficulty 方法试图使用枚举作为返回类型,然后返回类型而不是字段

  • Your enum is private, but your methods are public. Therefore you can't make your methods return type be the enum type, or have parameters with that type
  • Your SetDifficulty method has a parameter of just Difficulty - is that meant to be the parameter name or the type?
  • Your SetDifficulty method is trying to set the type rather than a field
  • Your GetDifficulty method is trying to use enum as a return type, and is then returning a type rather than a field

基本上,您似乎对您的枚举声明声明的内容感到困惑 - 它没有声明字段,它声明类型(并指定该类型的命名值是什么)。

Basically, you seem to be confused about what your enum declaration is declaring - it's not declaring a field, it's declaring a type (and specifying what the named values of that type are).

我怀疑你想要:

// Try not to use nested types unless there's a clear benefit.
public enum Difficulty { Easy, Normal, Hard }

public class Foo
{
    // Declares a property of *type* Difficulty, and with a *name* of Difficulty
    public Difficulty Difficulty { get; set; }
}

如果你真的想要编写代码,你可以使用get / set方法看起来像Java而不是C#:

You can use get/set methods if you really want to make your code look like Java instead of C#:

public enum Difficulty { Easy, Normal, Hard }

public class Foo
{
    private Difficulty difficulty;

    public void SetDifficulty(Difficulty value)
    {
        difficulty = value;
    }

    public Difficulty GetDifficulty()
    {
        return difficulty;
    }
}

这篇关于C#如何在类中使用get,set和use enums的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆