Activator.CreateInstance强制转换为在运行时键入

时间:2019-02-05 09:32:17

标签: c# .net generics reflection custom-attributes

我正在编写一个使用大量反射的小型框架,我想将我的代码分成多个项目,以提高可维护性。

主项目包含一个静态反射缓存,我在其中扫描所有程序集以查找某些类型,并将这些结果缓存以供将来在处理属性时使用。

此缓存根据在类上找到的属性类型生成一堆不同的属性上下文。即。

PropertyAttributeContext->应用于类/属性的通用属性 XmlPropertyAttributeContext->应用于类/属性的xml特定属性 JsonPropertyAttributeContext->应用于类/属性的json特定属性

这些类型在主项目中未定义。我想做的是,如果用户加载JsonProject,则该项目将自动注册自身并将其类型缓存到缓存中。这样,在初始化缓存时,将加载所有已注册的类型。具体类型都从同一个抽象基类扩展。

我找不到使用泛型执行此操作的方法,因为这将需要声明和迭代未绑定的ConcurrentBag,这是不可能的。

这是行不通的:

public class MetaDataEntry<I,T>
{
    public I Interface { get; set; }
    public T Type { get; set; }
}

class MetaDataRegistry
{
    // OOPS
    public static ConcurrentBag<MetaDataEntry<,>> Entries = new ConcurrentBag<MetaDataEntry<,>>(); 

    public void Register<I, T>()
    {
        Entries.Add(new MetaDataEntry<I,T>());
    }
}

因此,看来我仅限于使用typeof和Activator.CreateInstance实例化我的类型。我遇到的问题是我无法将创建的对象强制转换为它的派生类型。在下面,您可以看到我正在存储键类型为ConcurrentDictionary的实例以及派生实例的AbstractAttributeContext。

using ConcurrentDictionaryTypeContext = System.Collections.Concurrent.ConcurrentDictionary<System.Type, Integration.Cache.Context.AbstractAttributeContext>;

public class ClassMetaData
{
    private ConcurrentDictionary<PropertyInfo, ConcurrentDictionaryTypeContext> _propertyContexts;
    private ClassAttributeContext _classAttributeContext;
    private Type _classType;
    private PropertyInfo[] _properties;

    public ClassMetaData(Type type)
    {
        _classType = type;
        _classAttributeContext = new ClassAttributeContext(type);
        _properties = type.GetProperties(ReflectionUtils.GetPublicBindingFlags());
        _propertyContexts = new ConcurrentDictionary<PropertyInfo, ConcurrentDictionaryTypeContext>();


        foreach (PropertyInfo property in _properties)
        {
            ConcurrentDictionaryTypeContext propertyDictionary = new ConcurrentDictionaryTypeContext();

            foreach(MetaDataEntry entry in MetaDataRegistry.Entries)
            {
                if (ReflectionUtils.HasCustomAttributeType(entry.Interface, property))
                // ****** CANNOT CAST THIS TO CONCRETE TYPE ********
                    if (!propertyDictionary.TryAdd(entry.Type, Activator.CreateInstance(entry.Type, new object[]{ property })))
                        throw new ReflectionCacheException("Type " + type.AssemblyQualifiedName + " could not be added to the cache because property " + property.Name + " could not be added to cache");

            }

            if (!_propertyContexts.TryAdd(property, propertyDictionary))
                throw new ReflectionCacheException("Type " + type.AssemblyQualifiedName + " could not be added to the cache");
        }        
    }

    public Type Type { get { return _classType; } }

    public PropertyInfo[] Properties { get { return _properties; } }

    public ClassAttributeContext ClassAttributeContext { get { return _classAttributeContext; } }

    public AttributeContextType GetAttributeContextForProperty<AttributeContextType>(PropertyInfo property) where AttributeContextType : AbstractAttributeContext
    {
        return (AttributeContextType)_propertyContexts[property][typeof(AttributeContextType)];
    }

    public bool HasPropertyAttributeContext<AttributeContextType>(PropertyInfo property)
    {
        return _propertyContexts.ContainsKey(property) && _propertyContexts[property].ContainsKey(typeof(AttributeContextType));
    }

    public ConcurrentDictionaryTypeContext GetContextsForProperty(PropertyInfo property)
    {
        return _propertyContexts[property];
    }
}

public class MetaDataCache
{
    private static ConcurrentDictionary<Type, ClassMetaData> _classes = Initialize();
    private static ConcurrentDictionary<Type, ClassMetaData> Initialize()
    {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        var keyValuePairs = assemblies.Select((Assembly assembly) =>
        {
            var qq = assembly.GetTypes()
            .Where((Type type) => 
                {
                    return type.GetProperties(ReflectionUtils.GetPublicBindingFlags())
                               .Any((PropertyInfo property) => property.GetCustomAttributes(typeof(IAttributeMarker), true).Length > 0);
                }) 
            .Select((Type type) => new KeyValuePair<Type, ClassMetaData>(type, new ClassMetaData(type)));
            return qq;
        });

        return new ConcurrentDictionary<Type, ClassMetaData>(keyValuePairs.SelectMany(i => i));
    }

    public static ClassMetaData Get<T>()
    {
        return Get(typeof(T));
    }

    public static ClassMetaData Get(Type type)
    {
        if (_classes.ContainsKey(type))
            return _classes[type];
        else
        {
            // TODO: Include search for class level attributes
            if (ReflectionUtils.GetCustomAttributesForAllProperties<IAttributeMarker>(type).Length > 0)
            {
                if (!_classes.TryAdd(type, new ClassMetaData(type)))
                    throw new ReflectionCacheException("Type " + type.AssemblyQualifiedName + " could not be added to the cache");
                else
                    return _classes[type];
            }
            else
                throw new InvalidTypeException("Type " + type.AssemblyQualifiedName + " does not have any attributes applied to the class");
        }
    }

    public static bool Contains(Type type)
    {
        return _classes.ContainsKey(type);
    }
}

public class MetaDataEntry
{
    public Type Interface { get; set; }
    public Type Type { get; set; }
}

class MetaDataRegistry
{
    public static ConcurrentBag<MetaDataEntry> Entries = new ConcurrentBag<MetaDataEntry>();

    public void Register(Type interface_, Type type)
    {
        Entries.Add(new MetaDataEntry() { Interface = interface_, Type = type });
    }

    public void Register<I, T>()
    {
        Entries.Add(new MetaDataEntry() { Interface = typeof(I), Type = typeof(T) });
    }
}

这肯定有可能实现吗?

0 个答案:

没有答案