[英]How can I return two values but only show one in a textbox and hide the other in C#
I want to display only the quote in the quote textbox but I also want to display the quotee name in the quotee textbox the problem is I can only return one value if I return both values they kinda go together in the quote textbox我只想在报价文本框中显示报价,但我也想在报价文本框中显示报价人姓名问题是如果我在报价文本框中同时返回两个值,它们有点像 go
public static string DisplayQuote()
{
Dictionary<string, string> quotes = new Dictionary<string, string>();
quotes.Add("Dr. Seuss",
"\"You’re off to great places, today is your day. Your mountain is waiting, so get onyour way.\"");
quotes.Add("A.A. Milne",
"\"You’re braver than you believe, and stronger than you seem, and smarter than you think.\"");
quotes.Add("Willie Nelson", "\"Once you replace negative thoughts with positive ones, you’ll start having positive results.\"");
quotes.Add("Les Brown",
"\"In every day, there are 1,440 minutes. That means we have 1,440 daily opportunities to make a positive impact.\"");
quotes.Add("Dr Seuss",
"\"When you are enthusiastic about what you do, you feel this positive energy. It’s very simple.\"");
int index = 0;
for (int i = 0; i < 5; i++)
{
index = randomQuote.Next(quotes.Count);
}
_quote = quotes.Values.ElementAt(index).ToString();
_quotee = quotes.Keys.ElementAt(index).ToString();
return (_quote, _quotee).ToString();
}
My WPF:我的 WPF:
namespace DailyQuotes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DailyQuote daily = new DailyQuote();
txtQuotee.Text = daily.Quoteee;
txtPeriod.Text = daily.GetPeriod();
txtQuote.Text = daily.DisplayQuote();
txtTime.Text = daily.Time.ToString("h:mm tt");
}
}
}
Why don't you just return the tuple instead of calling ToString
on it?为什么不直接返回元组而不是调用ToString
呢?
public static (string quote, string quotee) DisplayQuote()
{
....
return (_quote, _quotee);
}
Then you can access the two returns like this:然后你可以像这样访问两个返回:
DailyQuote daily = new DailyQuote();
txtQuotee.Text = daily.quoeee;
txtQuote.Text = daily.quote;
This requires named tuples , which are available from C# 7.0 and onwards.这需要命名元组,可从 C# 7.0 及更高版本获得。 If you don't have C# 7.0 you'll need to use unnamed Tuples like so;如果您没有 C# 7.0,则需要像这样使用未命名的元组;
public Tuple<string,string> DisplayQuote()
{
...
return new Tuple<string,string>(_quote, _quotee);
}
var tuple = DisplayQuote();
txtQuotee.Text = tuple.Item1;
txtQuote.Text = tuple.Item2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.