C#控制台列格式和定位
我有几个关于控制台应用程序中列格式的问题。我的代码和输出如下C#控制台列格式和定位,c#,console,C#,Console,我有几个关于控制台应用程序中列格式的问题。我的代码和输出如下 为什么在第一个asdf之前有一个空格 为什么guid不像其他行那样排列 3.为什么当我指定{0,5}时,它会在第7个字符列之后开始打印 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person person = new Person { Id = Guid.NewGuid(), Name = "John", Email = "John@example.com", Phone = "123456789" };
Console.WriteLine("{0} DETAILS", person.Name.ToUpper());
Console.WriteLine("{0,5} {1,5}", "asfd", "asdf");
Console.WriteLine("Id: {0,5}", person.Id.ToString());
Console.WriteLine("Name: {0,5}", person.Name);
Console.WriteLine("Phone: {0,5}", person.Phone);
Console.WriteLine("Email: {0,5}", person.Email);
Console.ReadKey();
}
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}
}
这是我的控制台输出:
JOHN DETAILS
asfd asdf
Id: 21257c7f-dae0-4876-91bb-0fe88d926500
Name: John
Phone: 123456789
Email: John@example.com
为什么在第一个asdf之前有一个空格
由于{0,5}
中的,5
表示“对齐到5个字符”,而“asfd”仅为4个字符,因此空格用于填充
为什么guid不像其他行那样排列
您正在尝试对齐超过5列的整个ID,而许多字符无法“容纳”到5列中
为什么当我指定{0,5}时,它会在第7个字符列之后开始打印
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person person = new Person { Id = Guid.NewGuid(), Name = "John", Email = "John@example.com", Phone = "123456789" };
Console.WriteLine("{0} DETAILS", person.Name.ToUpper());
Console.WriteLine("{0,5} {1,5}", "asfd", "asdf");
Console.WriteLine("Id: {0,5}", person.Id.ToString());
Console.WriteLine("Name: {0,5}", person.Name);
Console.WriteLine("Phone: {0,5}", person.Phone);
Console.WriteLine("Email: {0,5}", person.Email);
Console.ReadKey();
}
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}
}
你在哪里看到这种情况
我假设您想要的是将所有内容对齐,因此您可以这样做:
Console.WriteLine("{0,5}: {1}", "Id", person.Id.ToString());
Console.WriteLine("{0,5}: {1}", "Name", person.Name);
Console.WriteLine("{0,5}: {1}", "Phone", person.Phone);
Console.WriteLine("{0,5}: {1}", "Email", person.Email);
这将把所有字段名对齐在一起。这是因为最长的字段名长度为5个字符。您可以将、5
更改为其他内容,如果它们都相同(且长度大于5),则所有字段名将通过在左侧填充空格右对齐
您可以在MSDN上阅读更多信息:
为什么在第一个asdf之前有一个空格
当您执行{0,5}
时,5代表的是“从{
所在的点开始右对齐文本5个空格”。因此,当您执行时,“asdf”
将变为“asdf”
为什么guid不像其他行那样排列
因为当你检查你指定的数字时,它开始左对齐文本,所以因为文本太长,添加,5
什么都不做
为什么当我指定{0,5}时,它会在第7个字符列之后开始打印
因为,5
不知道也不关心前面的文本。它只根据您放置占位符的位置进行偏移
有关如何正确对齐的代码示例,请参阅。使用比
John
长的名称,您将看到该名称也不对齐。好了,我键入的最后10分钟已经过去了。我正要发布一个相同的答案,我想我将对这一个进行投票。@networked感谢您提供的示例。这就是我正在尝试解决的问题chieve.two@networked和你的答案都很好,尽管我觉得这个答案解释了为什么我的尝试效果不好。我希望我能接受这两个答案。谢谢。