使用结构体作为参数
本文关键字:参数 结构体 | 更新日期: 2023-09-27 18:13:16
我需要定义具有十进制值的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'
edit:我需要我的r
参数只能接受给定范围的值,而不是任何double
值。这是同样的事情,如果我可以有一个enum
,可以接受十进制值,如上面我的struct
所述。
你的方法期望一个结构体值,而你给它一个const双精度值。
修改你的方法签名:
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_class
或myClass
。查看此MSDN页面
不能将double类型的值传递给需要struct类型的方法。要么将函数签名更改为double类型,要么在结构体中传递。SetRValue(产品。id, r_type);这取决于你在这里要做什么
要模拟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;
}
}