格式字符串中不使用参数

时间:2016-07-22 13:52:11

标签: c#

嘿伙计们,我确定这是否已被问过,但我找不到了。如果它是多余的我很抱歉。请把我链接到它。我的问题是:

错误“格式字符串中没有使用参数”是什么意思? 我正在使用C#

using System;

class PrintNum
{


    static void Main()
    {

        short s = 10;
        int i = 1000;
        long l = 1000000;
        float f = 230.47f;
        double d = 30949.374;


        //This is where I'm getting the error. 
        Console.Write("s: %d\n", s); //<<< if you hover over the variable s on the outside.
        Console.Write("i: %d\n", i);
        Console.Write("l: %ld\n", l);
        Console.Write("f: %.3f\n", f);
        Console.Write("d: %.3f\n", d);

    }
}

3 个答案:

答案 0 :(得分:2)

您的格式字符串不正确。它应该像

__init__

其中格式字符串中的class Base(object): def __init__(self, arg1, arg2, arg3, arg4): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 class Child(Base): def __init__(self, arg1, arg2, arg3, arg4, arg5): super(Child, self).__init__(arg1, arg2, arg3, arg4) self.arg5 = arg5 表示“格式字符串后传递的第一个参数”,Console.Write("s: {0}\n", s); 表示第二个参数(如果有),依此类推。

与C不同,{C}格式字符串中不使用{0}和类似的格式参数,并且使用{1}方法覆盖您正在使用的类型处理此格式。

答案 1 :(得分:0)

使用{0}将您的参数插入字符串,0作为参数编号:

Console.Write("s: {0}\n", s);

如果您想进一步格式化数字,请查看the documentation

此外,还有Console.WriteLine方法可以避免在字符串末尾添加换行符。

答案 2 :(得分:0)

与其他答案一样,您的Console.Write需要包含&#34; {0}&#34;因为那是你正在写的变量的占位符。重要的是要注意{0},{1}等是位置参数,并且必须在字符串中遵循该顺序。知道Console.Write在下面使用String.Format也很重要,因此你可以使用标准数字格式字符串(https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx)中描述的所有格式字符串。)话虽如此,我认为这是什么您正在寻找:

// generate the cache
Dictionary<string, object> setters = new Dictionary<string, object>();
Type t = this.GetType();
foreach (FieldInfo fld in t.GetFields()) {
     MethodInfo method = t.GetMethod("CreateSetter");
     MethodInfo genericMethod = method.MakeGenericMethod( new Type[] {this.GetType(), fld.FieldType});
     setters.Add(fld.Name, genericMethod.Invoke(null, new[] {fld}));
}
// now how would I use these setters?
setters[fld.Name].Invoke(this, new object[] {newValue}); // => doesn't work without cast....

输出:

sing System;

public class Test
{
    public static void Main()
    {
        short s = 10;
        int i = 1000;
        long l = 1000000;
        float f = 230.47f;
        double d = 30949.374;

        Console.WriteLine("s: {0:D}", s);
        Console.WriteLine("i: {0:D}", i);
        Console.WriteLine("l: {0:D}", l);
        Console.WriteLine("f: {0:F}", f);
        Console.WriteLine("d: {0:F}", d);
    }
}