Possible Duplicate:
Dynamically implementing an interface in .NET 4.0 (C#)
cast anonymous type to an interface?
有没有办法将匿名类型“转换”为特定接口(interface)?我知道我可以创建一个实现这个接口(interface)的类,但我不需要这个类,我必须返回一个接口(interface)。
我需要一个没有第三方库的解决方案
谢谢,
var result =
(from a in context.TABLE1
join b in context.TABLE2 on a.Table2Id equals b.Id
select new
{
Table1Field1 = a.Field1,
Table2Field1 = b.Field1,
....
}).ToList<IMyClass>();
public interface IMyClass
{
string Table1Field1 { get; set; }
string Table1Field2 { get; set; }
string Table2Field1 { get; set; }
}
这是不可能的。为什么?因为匿名类型是一种语法糖。匿名类型是一种设计时功能,这意味着编译器将生成一个名称非常奇怪的实际类型,但毕竟它与任何其他类型一样。
遗憾的是,C# 没有接口(interface)自动实现。也就是说,您需要在命名 类型中实现一个接口(interface)。
更新
想要解决此限制?
您可以使用控制反转(使用像 CaSTLe Windsor 这样的 API 或只是手动)。
检查我刚才制作的示例代码:
public static class AnonymousExtensions
{
public static T To<T>(this object anon)
{
// #1 Obtain the type implementing the whole interface
Type implementation = Assembly.GetExecutingAssembly()
.GetTypes()
.SingleOrDefault(t => t.GetInterfaces().Contains(typeof(T)));
// #2 Once you've the implementation type, you create an instance of it
object implementationInstance = Activator.CreateInstance(implementation, false);
// #3 Now's time to set the implementation properties based on
// the anonyous type instance property values!
foreach(PropertyInfo property in anon.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
// Has the implementation this anonymous type property?
if(implementation.GetProperty(property.Name) != null)
{
// Setting the implementation instance property with the anonymous
// type instance property's value!
implementation.GetProperty(property.Name).SetValue(implementationInstance, property.GetValue(anon, null));
}
}
return (T)implementationInstance;
}
}
设计并实现一些接口(interface)...
// Some interface
public interface IHasText
{
string Text { get; set; }
}
// An implementation for the interface
public class HasText : IHasText
{
public string Text
{
get;
set;
}
}
现在在某处使用整个扩展方法!
var anonymous = new { Text = "Hello world!" };
IHasText hasTextImplementation = anonymous.To<IHasText>();
hasTextImplementation
将有一个 HasText
实现实例!或者换句话说:Text
属性将包含 Hello world!。
请注意,可以调整此代码以支持基类和抽象类,但我相信这足以获取基本信息以根据您的需要改进它。