微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果存在被调用的方法,为什么会出现Microsoft.CSharp.RuntimeBinder.RuntimeBinderException?

如何解决如果存在被调用的方法,为什么会出现Microsoft.CSharp.RuntimeBinder.RuntimeBinderException?

| 我有以下代码,用于创建分配给smtpClient变量的动态对象。
public class TranferManager
{
    public void Tranfer(Account from,Account to,Money amount)
    {
        // Perform the required actions
        var smtpClient = New.SmtpClient();
        smtpClient.Send(\"info@bank.com\",\"from.Email\",\"Tranfer\",\"?\");
        // In the prevIoUs line I get a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
        // with the description = \"\'object\' does not contain a deFinition for \'Send\'\"
    }
}

public static class New
{
    public static dynamic SmtpClient(params object[] parameters)
    {
        return typeof(SmtpClient).New(parameters);
    }
}

public static class CreationExtensions
{
    private static Dictionary<Type,Func<object,dynamic>> builders =
        new Dictionary<Type,dynamic>>();

    public static dynamic New(this Type type,params object[] parameters)
    {
        if(builders.ContainsKey(type))
            return builders[type](parameters);

        return Activator.CreateInstance(type,parameters);
    }

    public static void RegisterBuilder(this Type type,dynamic> builder)
    {
        builders.Add(type,builder);
    }
}
要测试它,我使用的是UT(如下):
    [TestMethod()]
    public void Tranfertest()
    {
        typeof(SmtpClient).RegisterBuilder(p => 
            new
            {
                Send = new Action<string,string,string>(
                (from,to,subject,body) => { })
            }
        );

        var tm = new TranferManager();
        tm.Tranfer(new Account(),new Account(),new Money());
        // Assert
    }
当我使用中间窗口询问我得到的smtpClient类型时:
smtpClient.GetType()
{<>f__AnonymousType0`1[System.Action`4[System.String,System.String,System.String]]}
当我请求其成员时,我得到:
smtpClient.GetType().GetMembers()
{System.Reflection.MemberInfo[7]}
    [0]: {System.Action`4[System.String,System.String] get_Send()}
    [1]: {System.String ToString()}
    [2]: {Boolean Equals(System.Object)}
    [3]: {Int32 GetHashCode()}
    [4]: {System.Type GetType()}
    [5]: {Void .ctor(System.Action`4[System.String,System.String])}
    [6]: {System.Action`4[System.String,System.String] Send}
所以,我的问题是:为什么我会收到该例外?     

解决方法

匿名类型是内部的,如果您跨装配边界
dynamic
无法解析该属性。 与其使用匿名类型,不如尝试使用实际类型或Expando对象。     ,在AssemblyInfo.cs中,尝试添加以下内容:
[assembly: InternalsVisibleTo(\"NameSpace1.SubNameSpace1\")]
其中NamsSpace1是您的项目名称,SubNameSpace是您的动态/匿名对象的名称空间     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。