实际答案在答案注释中。我原本希望获得界面的“实例”,而这是做不到的。
-
我找到了一种方法来做我真正想要的,对于感兴趣的人,我在下面概述了。
public interface Interface<T> { Func<T,T> Property { get; set; } }
public class Concrete : Interface<string>
{
public Concrete()
{
(this as Interface<string>).Property = (s) => { return $"hello, {s}!"; };
}
Func<string, string> Interface<string>.Property
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
object obj = new Concrete();
var propInfo = obj.GetType().GetInterfaces().Single().GetProperty("Property");
dynamic func = propInfo.GetMethod.Invoke(obj, null);
var output = func("world");
}
}
-
我正在做一些代码生成并大量使用动态类型,但是不幸的是我遇到了动态类型/显式接口的难题。
我可以通过使用此处Convert.ChangeType(...)
概述的方法来解决此问题,但是它要求IConvertable
实现该方法,这会产生我不想做的大量开销。
我找到了一个使用Linq表达式使用Expression.TypeAs
或进行此操作的示例Expression.Convert
,但是它总是返回基础的具体类型,而不是我需要的接口。
这是我要执行的代码示例:
namespace ExpressionCasting
{
public interface Interface<T> { void Method(T t); }
public class ImplementedInterface : Interface<string>
{
void Interface<string>.Method(string t) { }
}
class Program
{
static void Main(string[] args)
{
var implementedInterface = new ImplementedInterface();
// type is an IInterface<string>
var type = implementedInterface.GetType().GetInterfaces().Single();
// i is always an ImplementedInterface
var i = Convert(type, implementedInterface); // i is always an ImplementedInterface
Console.WriteLine(i.GetType()); // i want this to be an IInterface<string> nit and ImplementedInterface.
}
static object Convert(Type type, object subClass)
{
var body = Expression.TypeAs(
Expression.Constant(subClass, subClass.GetType()), type);
var run = Expression.Lambda(
body, Expression.Parameter(subClass.GetType())).Compile();
return run.DynamicInvoke(subClass);
}
}
}
有什么想法可以让我得到所需的表达式吗,或者还有其他我没想到的选择?
问题不在于您的表情。它与动态的使用有关。DLR不在考虑显式接口实现。由于以下代码返回相同的异常,因此很容易证明:
dynamic i = new ImplementedInterface();
i.Method(); // throws exception as method is not found.
这是关于此问题的小文章,以及使用动态时的其他惊喜:http : //csharpindepth.com/Articles/Chapter14/DynamicGotchas.aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句