gpt4 book ai didi

c# - 从 C# 中的结构构建逗号分隔的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:06 25 4
gpt4 key购买 nike

我在 C# 类中有以下结构

public struct Employee
{
public const string EMPID = "EMP_ID";
public const string FName = "FIRST_NAME";
public const string LNAME = "LAST_NAME";
public const string DEPTID = "DEPT_ID";

}

有没有一种简单的方法来构建一个字符串,如下所示

const string mainquery="INSERT INTO EMP(EMP_ID,FIRST_NAME,LAST_NAME,DEPT_ID) VALUES(:EMP_ID,:FIRST_NAME,:LAST_NAME,:DEPT_ID)"

而不是像下面那样做然后连接它。

const string EMP_COLS=
EMPLOYEE.EMPID + "," +
EMPLOYEE.FNAME + "," +
EMPLOYEE.LNAME + "," +
EMPLOYEE.DEPTID;

const string EMP_Values=
EMPLOYEE.EMPID + ":" +
EMPLOYEE.FNAME + ":" +
EMPLOYEE.LNAME + ":" +
EMPLOYEE.DEPTID;

最佳答案

你可以尝试这样的事情:

StringBuilder sb = new StringBuilder();
var fields = typeof(Employee).GetFields();
for (int i = 0; i < fields.Length; ++i)
{
sb.Append(fields[i].GetValue(new Employee()));
if (i < fields.Length - 1)
{
sb.Append(',');
}
}

string result = sb.ToString();
// The above will be "EMP_ID,FIRST_NAME,LAST_NAME,DEPT_ID"

编辑:请注意,上面我假设您已经为 System.ReflectionSystem.文字.

关于c# - 从 C# 中的结构构建逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3045568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com