[英]How do I get the values from static properties on a static class?
[英]How do I use snippets to get properties from the current class?
我是否可以創建一個代碼片段並分析當前的類,獲取所述類的屬性,然后創建一個sql函數,以逐行寫出命令參數中的每個屬性。
我正在尋找的是做這樣的事情:
public static int Add(MyObject Message) {
MySqlConnection connection = new MySqlConnection(MySqlConnection);
MySqlCommand command = new MySqlCommand("Add_Message", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@IMFromUserID", Message.IMFromUserID);
command.Parameters.AddWithValue("@IMToUserID", Message.IMToUserID);
command.Parameters.AddWithValue("@IMMessage", Message.IMMessage);
command.Parameters.AddWithValue("@IMTimestamp", Message.IMTimestamp);
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
Message.IMID = (int)reader["IMID"];
}
command.Dispose();
connection.Close();
connection.Dispose();
return Message.IMID;
}
基本上,我希望代碼片段填充整個Add函數並在command.Parameters.AddWithValue
填充@PropertyName
和Message.PropertyName
我認為代碼片段不夠強大。 ReSharper的代碼模板也許功能足夠強大,但我也不這么認為。 如果您確實需要或想要生成代碼,則可以考慮使用T4模板 。
我個人建議完全避免編譯時代碼生成。 您可以使用反射-簡單但緩慢-或運行時代碼生成-復雜但快速。 如果性能不是主要考慮因素,則建議使用反射。
public static Int32 Add<TMessage>(TMessage message)
where TMessage: IMessageWithIMID
{
using (var connection = new MySqlConnection(connectionString))
using (var command = new MySqlCommand("Add_Message", connection))
{
command.CommandType = CommandType.StoredProcedure;
// We look only at public instance properties but you can easily
// change this and even use a custom attribute to control which
// properties to include.
var properties = typeof(TObject).GetProperties(BindingFlags.Public |
BindingFlags.Instance);
foreach (var property in properties)
{
var parameterName = "@" + property.Name;
var value = property.GetValue(message, null);
command.Parameters.AddWithValue(parameterName, value);
}
connection.Open();
message.IMID = (Int32)command.ExecuteScalar();
return message.IMID;
}
}
請注意,您必須引入並實現接口IMessageWithIMID
才能訪問屬性IMID
。
internal interface IMessageWithIMID
{
Int32 IMID { get; set; }
}
請注意,您也不需要讀取數據-您可以使用ExecuteScalar()
。 這變成
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
message.IMID = (Int32)reader["IMID"];
}
}
進入
message.IMID = (Int32)command.ExecuteScalar();
到此為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.