这是不可能的。为什么?因为匿名类型是一种语法糖。 匿名类型是设计时特性,意味着编译器将生成一个具有非常奇怪名称的实际类型,但它毕竟像任何其他类型一样。
不幸的是,C#没有自动实现接口。也就是说,您需要在已命名的类型中实现接口。
更新
想要解决这个限制吗?
您可以使用控制反转(使用类似于Castle Windsor的API或手动实现)。
请查看我刚刚编写的此示例代码:
public static class AnonymousExtensions
{
public static T To<T>(this object anon)
{
Type implementation = Assembly.GetExecutingAssembly()
.GetTypes()
.SingleOrDefault(t => t.GetInterfaces().Contains(typeof(T)));
object implementationInstance = Activator.CreateInstance(implementation, false);
foreach(PropertyInfo property in anon.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if(implementation.GetProperty(property.Name) != null)
{
implementation.GetProperty(property.Name).SetValue(implementationInstance, property.GetValue(anon, null));
}
}
return (T)implementationInstance;
}
}
设计并实现一些接口...
public interface IHasText
{
string Text { get; set; }
}
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!。
请注意,此代码可以进行微调,以支持基类和抽象类,但我相信这已足够提供基本信息,以便您根据自己的需求进行改进。