问题描述:

I want to set the Text of a TextBlock according to the Value of a Random Number

I thought about using toString for getting the String of the Random number

and then assigning it to the TextBlock

My Code:

 Random Rnd = new Random();

Number1 = Rnd.Next(1, 12);

Number2 = Rnd.Next(1, 12);

num1.Text = Number1.ToString;

num2.Text = Number2.ToString;

When I run the code

and it gives me the following error:

Cannot convert method group 'ToString' to non-delegate type 'string'.

Did you intend to invoke the method?

But both side's types are String , why can't I assign it ?

网友答案:

The problem is that you're not calling the ToString method. In this statement:

num1.Text = Number1.ToString;

... ToString is a method group, which can be used for conversions to delegate types. So for example, this is valid:

Func<string> stringProvider = Number1.ToString;

That's why the error message talks about method groups.

For a method invocation, however, you definitely need the brackets. This is a difference between C# and VB. (In VB, you'd need AddressOf to create a delegate for a method group, but don't need to specify the brackets when invoking a parameterless method.)

You need:

num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

(Additionally, I strongly suggest you follow normal C# naming conventions, where non-constant variables are camelCased rather than PascalCased, but that's a slightly different matter.)

网友答案:
num1.Text = Number1.ToString;
num2.Text = Number2.ToString;

Isn't valid c# syntax.

You could use:

num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

Or

num1.Text = Convert.ToString(Number1);
num2.Text = Convert.ToString(Number2);

Where Convert.ToString handles null values and value.ToString() doesn't.

网友答案:

Try this as .Next() returns an int

num1.Text = Number1.ToString();
num2.Text = Number2.ToString();
网友答案:

you need to convert Number1 and Number2 to string like

num1.Text = Number1.ToString();
num2.Text = Number2.ToString();
网友答案:

You have to convert Number1 and Number2 to string before assigning it to a text box like

  num1.Text=Number1.ToString();
  num2.Text=Number2.ToString();
相关阅读:
Top