我目前无法理解为什么第二次调用下面方法的输出不同。
/// <summary>
/// Method which given an object will produce the sql string part.
/// </summary>
/// <typeparam name="T">Object type</typeparam>
/// <param name="modelObject">The object to assess</param>
/// <param name="param">true if appending @ (aka parameter)</param>
/// <returns>the string part of the sql.</returns>
public static string GetInsertParamString<T>(T modelObject, bool param = false)
{
//simple stringbuilder to hold the string we will return
StringBuilder str = new StringBuilder();
//loop through each of the proporties of the object
foreach (PropertyInfo prop in modelObject.GetType().GetProperties())
{
//if the value of this object is not null - then add to the string
if (modelObject.GetType().GetProperty(prop.Name)?.GetValue(modelObject, null) != null)
{
//if param == true then add the @ before.
str.Append(param ? "@" + prop.Name : prop.Name).Append(",");
}
}
//return the string.
return str.ToString().Remove(str.Length - 1, 1);
}
我正在使用以下 C# 代码行调用该方法:
private static string InsertCrmSql<T>(T obj, string table) => @"INSERT INTO " + table + @" (" + SqlHelper.GetInsertParamString(obj) + @") VALUES (" + SqlHelper.GetInsertParamString(obj) + @")";
这表明使用完全相同的参数调用该方法两次。 注意:为了调试,我已经从第二次调用中删除了真实值以确保这不会导致问题。
在第一次调用该方法后在调试中运行时,将返回以下内容:
{wc_id,wc_status,wc_custref,wc_cuname,wc_transid,wc_transtype,wc_reqdate,wc_store,wc_salesman,wc_analysis1,wc_analysis2,wc_analysis3,wc_analysis4,wc_analysis5,wc_analysis6,wc_analysis7,wc_analysis8,wc_analysis9,}
但是在第二次调用时发现以下内容:
{wc_analysis1,wc_analysis2,wc_analysis3,wc_analysis4,wc_analysis5,wc_analysis6,wc_analysis7,wc_analysis8,wc_analysis9,wc_id,wc_status,wc_custref,wc_cuname,wc_transid,wc_transtype,wc_reqdate,wc_store,wc_salesman,}
是否有人能够提供见解或解释为什么会发生这种情况?
我还应该在每次程序运行时添加相同的内容 - 第一个结果,然后是第二个结果
干杯
最佳答案
这很可能是因为,来自 documentation Type.GetProperties()
的:
The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.
您可能已经注意到 - 两个字符串中的名称相同,只是顺序不同。
所以需要按照一致的顺序枚举属性,比如:
foreach (PropertyInfo prop in modelObject.GetType().GetProperties().OrderBy(c => c.Name))
关于c# - 方法返回不同的字符串第二次调用 - 参数相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787225/