- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试向我们的 IoC 容器添加通用服务支持,但我有一个问题。
假设我有以下类型:
public interface IService<T> { ... }
public class Service<T> : IService<T> { ... }
然后是下面的代码:
Type type = typeof(Service<>); // <-- notice no specific type here
ConstructorInfo ctor = LogicToFindCtor(type); // <-- picks one of the ctors
现在,有了这个,我有了一个泛型类型和一个我无法调用的构造函数,因为它是通过具有泛型参数的泛型类型获得的。
因此,鉴于我在我的代码中尝试解析特定类型,比如 IService<Employee>
,我可以很容易地通过我的代码找到我需要使用具体类型 Service<T>
来解决这个问题,并且我需要注入(inject)类型 Employee
在T
.
但是,我的问题是:鉴于我已经在通用非特定类型上找到了我想要调用的构造函数,我如何找到特定类型的正确构造函数。
Type specificType = typeof(Service<Employee>);
ConstructorInfo specificCtor = MapGenericToSpecific(ctor, specificType);
编辑:我注意到属性 MetaDataToken两个构造函数(来自非特定类型的构造函数和来自特定类型的构造函数)在这里具有相同的值,我可以使用它来匹配吗?它仍然需要一个循环来找到正确的构造函数,但是用一个简单的 if 语句来找到正确的构造函数的循环比查看参数并尝试以这种方式匹配要好得多。我已经更改了下面的代码。现在可以编译运行了,有没有更好的反射更少的方法,也许直接在构造函数表中查找以根据 metadatatoken 值找到构造函数?
代码如下:
using System;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
namespace ConsoleApplication10
{
public class ActivationAttribute : Attribute { }
public class TestClass<T1, T2>
{
public TestClass(String p1)
{
Console.Out.WriteLine("Wrong constructor");
}
[Activation]
public TestClass(T1 p1)
{
Console.Out.WriteLine("Right constructor, p1=" + p1);
}
public TestClass(T2 p2)
{
Console.Out.WriteLine("Wrong constructor");
}
public TestClass()
{
Console.Out.WriteLine("Wrong constructor");
}
public TestClass(T1 p1, T2 p2)
{
Console.Out.WriteLine("Wrong constructor");
}
public TestClass(String p1, T2 p2)
{
Console.Out.WriteLine("Wrong constructor");
}
public TestClass(String p1, Int32 p2)
{
Console.Out.WriteLine("Wrong constructor");
}
}
public class Program
{
static void Main(string[] args)
{
// This is the type I have in my IoC container
Type genericType = typeof(TestClass<,>);
// This is the constructor I locate
ConstructorInfo genericCtor =
(from ctor in genericType.GetConstructors()
where ctor.IsDefined(typeof(ActivationAttribute), false)
select ctor).First();
Debug.Assert(genericCtor != null);
// RESOLUTION STEP
// Upon resolution, two actual types are specified
Type[] genericArguments = new Type[] { typeof(String), typeof(Int32) };
// So I create the actual type from the generic one
Type specificType = genericType.MakeGenericType(genericArguments);
// Can I look up the "genericCtor.MetadataToken" property directly?
// or is this as good as it gets?
ConstructorInfo specificCtor =
(from ctor in specificType.GetConstructors()
where ctor.MetadataToken == genericCtor.MetadataToken
select ctor).First();
Debug.Assert(specificCtor != null);
Debug.Assert(specificCtor != null, "No matching constructors was found");
Object instance = specificCtor.Invoke(new Object[] { "Test" });
Console.Out.Write("Press enter to exit...");
Console.In.ReadLine();
}
}
}
最佳答案
您可以依靠 MetadataToken 在有界和无界构造函数上保持相同。元数据是使用 IL 代码创建的,它是类型的一部分,与通用参数绑定(bind)无关。
.NET 不会为每次使用泛型参数创建不同的类型(例如 List<int>
和 List<bool>
)。它是相同的类型,但在每次调用时,有界泛型参数与方法参数一起传递到堆栈上(我知道你可能已经知道所有这些,但我只是在确定)。
因此,当类泛型参数绑定(bind)到特定类型时,附加到类型的 MetadataToken 在运行时不会更改。例如:
bool unboundAndBoundHasSameMetadataToken =
typeof(IList<>).MetadataToken == typeof(IList<int>).MetadataToken;
bool boundedClassesHasSameMetadataToken =
typeof(IList<bool>).MetadataToken == typeof(IList<int>).MetadataToken;
Assert.IsTrue(unboundAndBoundHasSameMetadataToken);
Assert.IsTrue(boundedClassesHasSameMetadataToken);
最重要的是,MetadataToken 是 IL 的“一部分”,并且在具有不同通用参数绑定(bind)的相同类型的实例上没有区别。
出于好奇(我可能遗漏了一些东西),为什么不使用在有界类型上查找 Activation 构造函数的过滤器,就像在未绑定(bind)类型上一样? Activation 属性也装饰了有界构造函数。
关于c# - C# 中的通用类型构造函数解析,适用于具有通用服务注册的 IoC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1588216/
我在我的 Xcode 项目目录中输入了以下内容: keytool -genkey -v -keystore release.keystore -alias mykey -keyalg RSA \
假设我有一个像这样的 DataFrame(或 Series): Value 0 0.5 1 0.8 2 -0.2 3 None 4 None 5 None
我正在对一个 Pandas 系列进行相对繁重的应用。有什么方法可以返回一些打印反馈,说明每次调用函数时在函数内部进行打印还有多远? 最佳答案 您可以使用跟踪器包装您的函数。以下两个示例,一个基于完成的
我有一个 DataFrame,其中一列包含列表作为单元格内容,如下所示: import pandas as pd df = pd.DataFrame({ 'col_lists': [[1, 2
我想使用 Pandas df.apply 但仅限于某些行 作为一个例子,我想做这样的事情,但我的实际问题有点复杂: import pandas as pd import math z = pd.Dat
我有以下 Pandas 数据框 id dist ds 0 0 0 0 5 1 0 0 7 2 0 0
这发生在我尝试使用 Gradle 构建时。由于字符串是对象,因此似乎没有理由发生此错误: No signature of method: java.util.HashMap.getOrDefault(
您好,有人可以解释为什么在 remaining() 函数中的 Backbone 示例应用程序 ( http://backbonejs.org/examples/todos/index.html ) 中
我有两个域类:用户 class User { String username String password String email Date dateCreated
问题陈述: 一个 pandas dataframe 列系列,same_group 需要根据两个现有列 row 和 col 的值从 bool 值创建。如果两个值在字典 memberships 中具有相似
apporable 报告以下错误: error: unknown type name 'MKMapItem'; did you mean 'MKMapView'? MKMapItem* destina
我有一个带有地址列的大型 DataFrame: data addr 0 0.617964 IN,Krishnagiri,635115 1 0.635428 IN,Chennai
我有一个列表list,里面有这样的项目 ElementA: Number=1, Version=1 ElementB: Number=1, Version=2 ElementC: Number=1,
我正在编译我的源代码,它只是在没有运行应用程序的情况下终止。这是我得到的日志: Build/android-armeabi-debug/com.app4u.portaldorugby/PortalDo
我正在尝试根据另一个单元格的值更改单元格值(颜色“红色”或“绿色”)。我运行以下命令: df.loc[0, 'Colour'] = df.loc[0, 'Count'].apply(lambda x:
我想弄清楚如何使用 StateT结合两个 State基于对我的 Scalaz state monad examples 的评论的状态转换器回答。 看来我已经很接近了,但是在尝试申请 sequence
如果我已经为它绑定(bind)了集合,我该如何添加 RibbonLibrary 默认的快速访问项容器。当我从 UI 添加快速访问工具项时,它会抛出 Operation is not valid whi
在我学习期间Typoclassopedia我遇到了这个证明,但我不确定我的证明是否正确。问题是: One might imagine a variant of the interchange law
我是一名优秀的程序员,十分优秀!