使用结构作为参数

eln*_*h78 -1 .net c#

我需要定义一个enum带小数值,但由于这是不可能的,我已经阅读了使用的解决方案struct,所以我有以下内容:

        public struct r_type
        {
            public const double c001_a1 = 0.1;
            public const double c001_a2 = 0.2;
            public const double c001_a4 = 0.4;
            public const double c001_a8 = 0.8;
        }
Run Code Online (Sandbox Code Playgroud)

我试图将其称为函数中的参数,如下所示:

public static void SetRValue(string product_id, r_type r)
Run Code Online (Sandbox Code Playgroud)

但是在我的代码中调用它时会出错:

SetRValue(product.id, r_type.c001_a1);
Run Code Online (Sandbox Code Playgroud)

错误是:

错误5参数2:无法从'double'转换为'myproject.class1.r_type'

编辑:我需要我的r参数只能接受给定范围的值,而不是任何double值.如果我能拥有一个enum可以接受我struct上面所述的十进制值的话,我会做同样的事情.

Kęd*_*rzu 7

您的方法需要一个struct值,而不是给它一个const double值.

更改方法签名:

public static void SetRValue(string product_id, double r)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以使用一个static class非常适合定义const值的:

public static class r_type
{
    public const double c001_a1 = 0.1;
    public const double c001_a2 = 0.2;
    public const double c001_a4 = 0.4;
    public const double c001_a8 = 0.8;
}
Run Code Online (Sandbox Code Playgroud)

您也可以将其缩小到这几个选项,但我怀疑它值得努力:

public class r_type { 

    // make it private not to create more than you want
    private r_type(double value) {
        this.Value = value;
    }

    public double Value { get; private set;}

    public static implicit operator double(r_type r)
    {
        return r.Value;
    }

    // your enum values below
    public static readonly r_type A1 = new r_type(0.1);
    public static readonly r_type A2 = new r_type(0.2);
    public static readonly r_type A4 = new r_type(0.2);
    public static readonly r_type A8 = new r_type(0.8);
}
Run Code Online (Sandbox Code Playgroud)

而你的方法:

public static void SetRValue(string product_id, r_type r)
{
    // you can use it explicitely
    var t = r.Value;
    // or sometimes even better, implicitely
    // thanks to implicit conversion operator
    double g = r;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:考虑使用一个完善的C#约定来调用你的类,MyClass而不是my_classmyClass.检查此MSDN页面.