C#: How do I initialize a custom class as shown below?
C#:如何初始化自定义类,如下所示?
Point3 Last = { 0, 0, 0 };
I realize that I can overload the assignment operator '=,' but I want to be able to assign things like this:
我意识到我可以重载赋值运算符'=,'但我希望能够分配这样的东西:
Point3 p1 = { 3, 4, 5 };
Point3 p2 = p1;
So I'm not really sure if overloading the assignment operator will help that or not.
所以我不确定重载赋值运算符是否有助于此。
What I'm looking at it the following:
我正在看它如下:
public static Point3 operator =(Point3 P, double[] Vs)
{
return new Point3(Vs[0], Vs[1], Vs[2]);
}
Any pointers?
1 个解决方案
#1
You can create an implicit operator like this:
您可以像这样创建一个隐式运算符:
public class Point3
{
public static implicit operator Point3(int[] ints)
{
return new Point3();
}
}
Which can be invoked using this:
可以使用以下方法调用:
Point3 p1 = new[] { 1, 2, 3 };
Note that you explicitly need to create the array and can't use the initializer expression. Basically what you do is interpret the right-hand side and provide an implicit conversion between that and your custom type. You can then define how exactly this conversion should be handled.
请注意,您明确需要创建数组,并且不能使用初始化表达式。基本上,您所做的就是解释右侧并提供它与您的自定义类型之间的隐式转换。然后,您可以定义应该如何处理此转换。
隐含在MSDN上
#1
You can create an implicit operator like this:
您可以像这样创建一个隐式运算符:
public class Point3
{
public static implicit operator Point3(int[] ints)
{
return new Point3();
}
}
Which can be invoked using this:
可以使用以下方法调用:
Point3 p1 = new[] { 1, 2, 3 };
Note that you explicitly need to create the array and can't use the initializer expression. Basically what you do is interpret the right-hand side and provide an implicit conversion between that and your custom type. You can then define how exactly this conversion should be handled.
请注意,您明确需要创建数组,并且不能使用初始化表达式。基本上,您所做的就是解释右侧并提供它与您的自定义类型之间的隐式转换。然后,您可以定义应该如何处理此转换。
隐含在MSDN上