c#依赖程序集的隐式转换抛出InvalidCastException

时间:2018-01-31 02:07:34

标签: c# casting

假设我有两个项目:

PROJECT1

一个类库

using System;

namespace Project1
{
    public class Foo
    {
        public Foo(object bar){
            Bar = (Bar)bar;
        }

        public Bar Bar { get;}
    }

    public class Bar{
        public string MyBar {get; set;}
    }
}

Project2的

一个exe

using System;
using Project1;

namespace Project2
{
    public class BarTrip
    {
        public string MyFoo {get;set;}

        public static implicit operator Bar(BarTrip trip){
            return new Bar{ MyBar = trip.MyFoo };
        }
    }

    public static class Program{
        public static void Main(params string[] args){
            var trip = new BarTrip(){ MyFoo = "Aaron" };
            var foo = new Foo(trip);

            Console.WriteLine(foo.Bar.MyBar);
        }
    }
}

我希望当我运行我的exe时,一旦BarTrip的构造函数中的转换操作被调用,我将在Foo内定义的隐式转换运算符被调用。

相反,我收到以下错误:

System.InvalidCastException: Unable to cast object of type 'Project2.BarTrip' to type 'Project1.Bar'.
   at Project1.Foo..ctor(Object bar)
   at Project2.Program.Main(String[] args) in D:\TestProjects\Project2\src\Project2\Program.cs:line 18

出现此错误的原因是什么?如果Project1是黑盒DLL,我该怎么做才能使这个方案可行?

1 个答案:

答案 0 :(得分:5)

编译时,没有类型信息传递给Foo构造函数的上下文,它只是object。那么隐含的演员表并没有得到解决。显式转换失败,因为没有明确定义的路径。

这似乎是类库中定义的接口的完美案例。

相关问题