是否可以使用结构作为string.Format
的参数,如下所示:
struct kid
{
public string name;
public int age;
};
kid.name = alice;
kid.age = 2;
Console.WriteLine(String.Format("Her name is {0} and she's {1} years old", kid));
而不是:
Console.WriteLine(String.Format("Her name is {0} and she's {1} years old", kid.name ,kid.age));
编辑:
将在运行时从配置文件
中读取该字符串答案 0 :(得分:7)
没有。它将如何知道要放在哪个属性?
你可以做的不是用这种方式键入string.Format
而是使用c#6.0字符串插值并将其写成:
Console.WriteLine($"Her name is {kid.name} and she's {kid.age} years old");
并且可以覆盖ToString()
以返回它:
struct kid
{
public override string ToString()
{
return $"Her name is {name} and she's {age} years old";
}
}
然后拨打Console.WriteLine(kid.ToString());
答案 1 :(得分:1)
由于.Format
的签名为String.Format(string format, params object[] args)
,因此您可以将结构转换为对象数组。
struct Kid
{
public string name;
public int age;
public object[] ToObjectArray()
{
return new object[] {
name, age };
}
public static implicit operator object[](Kid kid)
{
return kid.ToObjectArray();
}
};
class Program
{
static void Main(string[] args)
{
Kid kid=new Kid() { name="alice", age=2 };
Console.WriteLine("Her name is {0} and she's {1} years old", kid);
// Same as
// Console.WriteLine(string.Format("Her name is {0} and she's {1} years old", kid));
}
}
您还可以利用协方差并使用
将string[]
隐式转换为object[]
public string[] ToStringArray()
{
return new string[] {
name, age.ToString() };
}
public static implicit operator object[](Kid kid)
{
return kid.ToStringArray();
}
而不是ToObjectArray()
答案 2 :(得分:1)
您可以按结构实现IFormattable
接口,并通过格式字符串提供对不同属性的访问:
struct kid : IFormattable {
public string name;
public int age;
public override string ToString() => ToString(null, null);
public string ToString(string format, IFormatProvider provider) {
switch(format) {
case null:
case "":
return string.Format(provider, "({0:name}, {0:age})", this);
case "name":
return name.ToString(provider);
case "age":
return age.ToString(provider);
default:
throw new ArgumentOutOfRangeException(nameof(format));
}
}
}
然后你可以写如下:
Console.WriteLine("Her name is {0:name} and she's {0:age} years old", kid);
答案 3 :(得分:0)
有可能将结构作为数组访问:
如果kid是struct kidStr,那么kid [0]和kid [1]可以被定义为name和age.ToString()并在WriteLine中用作几个参数...应该对你有意义...
public string this[int i] {
get { return i == 0 ? name : age. ToString(); }
}
或更简单
public string[] ToArray() {
return new string[2]{ name, age.ToString()};
}
在struct kidStr中有上面的索引器和一个实例kid
Console.WriteLine("name is {0}, age is {1}", kid[0], kid[1]); // or kid.ToArray()