Return multiple values from a class to method(从一个类返回多个值到方法)
问题描述
我有一个将字符串传递给类的方法.出于测试原因,我现在使用了一个按钮.我在论坛中搜索过类似的问题,但它们指的是 php 和其他我无法理解的情况.该类从字符串中删除几个字符,并根据标题将值分配给 3 个不同的字符串.我需要将这 3 个字符串返回给调用者,并将其编码如下.
I have a method passing a string to a class. For testing reasons I have used a button for now. I have searched in the forum for similar questions but they refer to php and other situation that I am unable to understand. The class strips out few characters from the string and assign the value to 3 different strings depending on the header. I need to return those 3 strings back to the caller and I have coded it as following.
来电者:
private void button4_Click(object sender, EventArgs e)
{
string a, b, c;
string invia = textBox8.Text.ToString();
Stripper strp = new Stripper();
strp.Distri(invia, out a, out b, out c);
textBox7.Text = a;
textBox7.Text = b;
textBox7.Text = c;}
类:
class Stripper
{
public void Distri (string inArrivo, out string param1, out string param2, out string param3)
{
string corrente="";
string temperatura="";
string numGiri="";
string f = inArrivo;
f = f.Replace("<", "");
f = f.Replace(">", "");
if (f[0] == 'I')
{
string _corrente = f;
_corrente = _corrente.Replace("I", "");
corrente = _corrente;
}
else if (f[0] == 'T')
{
string _temperatura = f;
_temperatura = _temperatura.Replace("T", "");
temperatura = _temperatura;
}
else if (f[0] == 'N')
{
string _numGiri = f;
_numGiri = _numGiri.Replace("N", "");
numGiri = _numGiri;
}
param1 = corrente;
param2 = temperatura;
param3 = numGiri;
}
}
}
代码运行没有问题,但我不确定这是否是实现从类返回多个值的正确方法.有没有更好的办法?
The code is working without problems but I am not sure if this is the correct way to achieve the returning of multiple values from a class. Is there a better way?
推荐答案
我认为在这种情况下创建类更好
I think create class is better in this case
public class MyClass
{
public string Corrente { get; set; }
public string Temperatura { get; set; }
public string NumGiri { get; set; }
}
然后
public MyClass Distri(string inArrivo)
{
// your code
MyClass myclass = new MyClass() {
Corrente = corrente,
NumGiri = numGiri,
Temperatura = temperatura
};
return myclass;
}
你可以这样调用
Stripper strp = new Stripper();
MyClass myclass = strp.Distri(invia);
//访问值如下
textBox7.Text = myclass.NumGiri;
这篇关于从一个类返回多个值到方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从一个类返回多个值到方法
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01