我知道过早优化是万恶之母。但是,我想知道以下哪种替代方案更有效:
- 调用
typeof(T).GetProperties()
同一类型多次T
. - 将检索到的属性内存到
Dictionary<Type, PropertyInfo[]>
中.
这是我使用第一种方法编写的一些代码:
private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
T element = new T();
PropertyInfo[] properties = typeof(T).GetProperties(); // critical line
foreach (PropertyInfo property in properties)
property.SetValue(element, reader[property.Name], null);
return element;
}
public static T RetrieveElement<T>() where T : class, new() {
T element = null;
actions.Add(delegate(SqlDataReader reader) {
if (reader.Read())
element = MakeElement<T>(reader);
});
Execute();
return element;
}
public static List<T> RetrieveList<T>() where T : class, new() {
List<T> list = new List<T>();
actions.Add(delegate(SqlDataReader reader) {
while (reader.Read())
list.Add(MakeElement<T>(reader));
});
Execute();
return list;
}
// For the sake of completeness, here is the Execute method.
public static void Execute() {
SqlConnectionStringBuilder connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = DataSource;
connStringBuilder.InitialCatalog = InitialCatalog;
connStringBuilder.UserID = UserID;
connStringBuilder.Password = Password;
using (SqlConnection connection = new SqlConnection(connStringBuilder.ConnectionString))
using (SqlCommand command = new SqlCommand(StoredProcedure, connection)) {
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameterCollection = command.Parameters;
foreach (KeyValuePair<string, object> parameter in parameters)
parameterCollection.AddWithValue(parameter.Key, parameter.Value);
try {
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
foreach (Action<SqlDataReader> action in actions) {
action(reader);
reader.NextResult();
}
}
finally {
parameters.Clear();
actions.Clear();
}
}
}
我已经在思考哪种方法更有效:
直接调用 GetProperties
:
- 元数据无论如何都在那里。它不必重建,只需检索即可。
用于内存:
- 元数据的格式可能无法被 C# 应用程序直接理解,因此
GetProperties
中可能涉及一些预处理。 . - 元数据在那里,但是
PropertyInfo
的数组不是,因此必须重建。
最佳答案
我认为根据类型内存结果是可以的。你应该衡量你的情况,但我的经验是调用 GetProperties 或其他反射方法会带来性能损失。 GetProperties 的结果无论如何都不会在运行时改变。
关于c# - 使用 .NET 的反射 API 时内存类型元数据是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6417251/