使用结构作为参数

时间:2015-09-18 15:34:09

标签: c# .net

我需要定义带有小数值的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;
        }

我想在函数中将其称为参数,如下所示:

public static void SetRValue(string product_id, r_type r)

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

SetRValue(product.id, r_type.c001_a1);

错误是:

  

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

修改:我需要我的r参数只接受给定范围的值,而不是任何double值。如果我可以接受enum可以接受上面struct中所述的小数值,那么我会做同样的事情。

3 个答案:

答案 0 :(得分:7)

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

更改您的方法签名:

public static void SetRValue(string product_id, double r)

在这种情况下,您可以使用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;
}

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

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);
}

你的方法:

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;
}

BTW:考虑使用完善的C#惯例来调用类MyClass而不是my_classmyClass。检查this MSDN page

答案 1 :(得分:0)

您不能将double传递给期望结构的方法。更改函数签名以获取double或传入struct。 SetRValue(product.id,r_type); 这真的取决于你在这里要做什么。

答案 2 :(得分:0)

要模拟enum,您可以执行此操作:

public sealed class r_type
{
    private double Value;

    public static readonly r_type c001_a1 = new r_type(0.1);
    public static readonly r_type c001_a2 = new r_type(0.2);
    public static readonly r_type c001_a4 = new r_type(0.4);
    public static readonly r_type c001_a8 = new r_type(0.8);

    private r_type(double d)
    {
        Value = d;
    }

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

然后你可以像这样调用方法。

相关问题