【发布时间】:2011-03-08 17:55:57
【问题描述】:
情况如下: 我试图在我的程序集中获取所有类型的集合,这些类型实现了特定的泛型接口以及使用的泛型类型参数。我已经设法组合了一个 Linq 查询来执行此操作,但它似乎非常多余。
我已经阅读了 let 和 joins,但不知道如何使用它们来减少这个特定查询的冗长。任何人都可以提供有关如何缩短/增强查询的任何提示吗?
这是一个 MSTest 类,目前通过并演示了我想要实现的目标:
[TestClass]
public class Sample
{
[TestMethod]
public void MyTest()
{
var results =
(from type in Assembly.GetExecutingAssembly().GetTypes()
where type.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(MyInterface<,>)
)
select new ResultObj(type,
type.GetInterfaces().First(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(MyInterface<,>)
).GetGenericArguments()[0],
type.GetInterfaces().First(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(MyInterface<,>)
).GetGenericArguments()[1]
)).ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual(typeof(int), results[0].ArgA);
Assert.AreEqual(typeof(string), results[0].ArgB);
}
interface MyInterface<Ta, Tb>
{ }
class MyClassA : MyInterface<int, string>
{ }
class ResultObj
{
public Type Type { get; set; }
public Type ArgA { get; set; }
public Type ArgB { get; set; }
public ResultObj(Type type, Type argA, Type argB)
{
Type = type;
ArgA = argA;
ArgB = argB;
}
}
}
问候,
马特
【问题讨论】:
标签: linq generics reflection .net-3.5