从Type with Reflection获取类并使用Type in C#调用泛型构造函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了从Type with Reflection获取类并使用Type in C#调用泛型构造函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2189字,纯文字阅读大概需要4分钟。
内容图文
![从Type with Reflection获取类并使用Type in C#调用泛型构造函数](/upload/InfoBanner/zyjiaocheng/786/baa5775f942b4eb59be3788c8d6d8b0d.jpg)
我正在使用Dapper,我想迭代我的模型类,并为任何具有ColumnAttribute修饰的字段的类设置类型映射.
public class ColumnAttributeTypeMapper<T> : FallbackTypeMapper
{
public static readonly string ColumnAttributeName = "ColumnAttribute";
public ColumnAttributeTypeMapper()
: base(new SqlMapper.ITypeMap[]
{
new CustomPropertyTypeMap(typeof (T), SelectProperty),
new DefaultTypeMap(typeof (T))
})
{
}
// implementation of SelectProperty and so on...
// If required, full implementation is on https://gist.github.com/senjacob/8539127
}
在我的模型类库中,我正在迭代所有可能的类型;现在我需要调用泛型ColumnAttributeTypeMapper< T>具有类的类的构造函数.
using System.Web;
using Dapper;
[assembly : PreApplicationStartMethod(typeof(Model.Initiator), "RegisterTypeMaps")]
namespace Model
{
class Initiator
{
public static void RegisterTypeMaps()
{
var mappedTypes = Assembly.GetAssembly(typeof (Initiator)).GetTypes().Where(
f =>
f.GetProperties().Any(
p =>
p.GetCustomAttributes(false).Any(
a => a.GetType().Name == ColumnAttributeTypeMapper<dynamic>.ColumnAttributeName)));
// I want to skip registering each class manually :P
// SqlMapper.SetTypeMap(typeof(Model1), new ColumnAttributeTypeMapper<Model1>());
// SqlMapper.SetTypeMap(typeof(Model2), new ColumnAttributeTypeMapper<Model2>());
foreach (var mappedType in mappedTypes)
{
SqlMapper.SetTypeMap(mappedType, new ColumnAttributeTypeMapper<mappedType>());
}
}
}
}
如何将类从类型而不是类型’mappedType’传递给新的ColumnAttributeTypeMapper< classof(mappedType)?>()
我找到了this as a similar question,但我需要调用泛型构造函数而不是类型的泛型方法.
如果无法完成,请解释一下原因吗?
回答
这就是Tom所建议的映射工作方式.
var mapper = typeof(ColumnAttributeTypeMapper<>);
foreach (var mappedType in mappedTypes)
{
var genericType = mapper.MakeGenericType(new[] { mappedType });
SqlMapper.SetTypeMap(mappedType, Activator.CreateInstance(genericType) as SqlMapper.ITypeMap);
}
解决方法:
您将需要方法Type.MakeGenericType;用法如下:
var columnType = typeof(ColumnAttributeTypeMapper<>);
var genericColumn = columnType.MakeGenericType(new[] {typeof(mappedType)});
var instance = Activator.CreateInstance(genericColumn);
我写这篇文章没有智能感知,只是浏览了你的代码,所以请让我知道我是否犯过任何错误,我会纠正它们.
内容总结
以上是互联网集市为您收集整理的从Type with Reflection获取类并使用Type in C#调用泛型构造函数全部内容,希望文章能够帮你解决从Type with Reflection获取类并使用Type in C#调用泛型构造函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。