如何使用结构上的ref修改值。c#
这是我的代码:如何使用结构上的ref修改值。c#,c#,C#,这是我的代码: class Program { struct Ball { public string name; public int num; public string city; public torneoCanicas(string name, int num, string city) { this.name= name;
class Program
{
struct Ball
{
public string name;
public int num;
public string city;
public torneoCanicas(string name, int num, string city)
{
this.name= name;
this.num = num;
this.city= city;
}
}
static void Main(string[] args)
{
Ball joan = new Ball("JOAN",12,"Vilanova");
所以我想用ref修改这个结构的值。有人知道怎么做吗?
比如:
这是行不通的。
我想使用一种能够“全局”修改数据的结构。
我知道为了能够修改,我需要使用引用,但我不知道如何在结构中使用它。
还有另一种方法吗?您只需通过引用传递它,这样它就不会被复制到您的方法中:
static void modify(ref Ball ball){
ball.name="New name";
ball.num=54;
ball.city="Barcelona";
}
并调用您的方法,如:
modify(ref joan); // joan is the name of the variable in your example
我在这里做了一个样本:
顺便说一下,您的命名约定很难遵循:-)
PS:也就是说,确保您确实需要一个
struct
,而不是class
(您不需要任何ref
来做您想要的事情)。解释它们之间的差异将远远超出这个问题的范围。您的示例中没有数组,并且您的构造函数名torneoCanicas
与您的结构名balls
不同,您应该使用nameball
而不是balls
,它应该以大写字母开头:Ball
感谢您抽出时间来分享您的问题。你要什么还不清楚。你的目标和困难是什么?到目前为止你做了什么?请尝试更好地解释您的问题、开发环境和数据结构,以及或多或少地共享代码(无屏幕截图)、屏幕图像或草图、用户故事或场景图。为了帮助您改进您的请求,请阅读&。您可以添加更多代码并检查/澄清您的问题吗?什么阵列?什么ref
?假设你有一个数组,有这样一个结构,你不能修改这个结构,你必须用一个新的覆盖它。对于您的用例,您可能希望查看类而不是结构。
modify(ref joan); // joan is the name of the variable in your example