![](/img/trans.png)
[英]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.