我有一个模特:
public class Model
{
public int Id { get;}
public string Name { get; }
public string AnotherName { get; }
}
默认构造函数,没有设置方法,因此IL生成的类中没有公共设置方法。
但是Dapper
以某种方式初始化我的数据。所有属性均已填写。
var sql = $@"SELECT id as Id, name as Name, another_name as AnotherName FROM dapper";
var raws = (connection.QueryAsync<Model>(sql).Result).AsList();
我已经找到源代码,并且它们通过Setter方法进行设置,但是当我尝试像Dapper
那样获取setter时,我得到了null methodInfo。这是一些Dapper
源代码SqlMapper:3320
if (specializedConstructor == null)
{
// Store the value in the property/field
if (item.Property != null)
{
il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type));
}
else
{
il.Emit(OpCodes.Stfld, item.Field); // stack is now [target]
}
}
和DefaultTypeMap.GetPropertySetter
:
internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
{
if (propertyInfo.DeclaringType == type) return propertyInfo.GetSetMethod(true);
return propertyInfo.DeclaringType.GetProperty(
propertyInfo.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder,
propertyInfo.PropertyType,
propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(),
null).GetSetMethod(true);
}
您可以编写示例,我也可以这样做,您将看到您的属性是否没有任何设置方法,那么设置方法的信息将为null。