无法投C# [英] Unable to cast C#

查看:112
本文介绍了无法投C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的解决方案2不同的项目。



在我有一个名为MyClass1的类,在其他的我有MyClass2
这些类相同的,但在所有的名字。



在一个项目我有对象的列表。在运行期间被充满MyClass1的对象列表是
,我们铸造的对象。



最后我想投的每个对象列表中的一个MyClass2对象。



目前它抛出一个异常说无法投类型MyClass1的到MyClass2的对象。



我的代码

 列表<对象> _tempObjects =新的List<对象和GT;(); 
的foreach(在_tempObjects对象myObjectInput)
{
MyClass2 TEMP =(MyClass2)myObjectInput; //这里是它死
}



这两个类都是一样的,只是不同名。
我也尝试:

  MyClass2 TEMP = myObjectInput为MyClass2; 


解决方案

铸造不会这样的。当铸造对象为另一种类型(静态地称为对象)时,它必须已经是该类型为它工作的一个实例。也许你想从一个转换到另一个使用 AutoMapper ,如:

  Mapper.CreateMap< MyClass1的,MyClass2>(); 

//后...
MyClass2 TEMP = Mapper.Map< MyClass2>(myObjectInput);

或手动复制的属性,也许在构造函数:

 公共MyClass2(MyClass1的除外)
{
this.SomeProperty = other.SomeProperty;
//等
}

MyClass2临时=新MyClass2((MyClass1的)myObjectInput);






更可能的是,你应该做的是<强>使在.NET理解和本地支持的方式的项目共享 MyClass的 :通过把它可由这两个项目所引用的项目。如果一个项目应参考其他的,做到这一点;否则,创建第三个项目作为库。


I have 2 different projects in my solution.

In one I have a class called MyClass1, and in the other I have MyClass2 These classes are identical in all but name.

In one project I have a list of Objects. During runtime the list gets filled with MyClass1 objects that we casted to an object.

At the end I want to cast each object in the list to a MyClass2 object.

Currently it throws an exception saying Unable to cast object of type MyClass1 to MyClass2.

My Code:

List<Object> _tempObjects = new List<Objects>();
foreach(Object myObjectInput in _tempObjects)
{
  MyClass2 temp = (MyClass2) myObjectInput; // here is where it dies
}

The two classes are the same, just different names. I have also tried:

 MyClass2 temp = myObjectInput as MyClass2; 

解决方案

Casting doesn't work that way. When casting (an object statically known as) object to another type, it must already be an instance of that type for it to work. Maybe you'd like to convert from one to the other with AutoMapper, e.g.

Mapper.CreateMap<MyClass1, MyClass2>();

// later...
MyClass2 temp = Mapper.Map<MyClass2>(myObjectInput);

Or manually copy the properties, maybe in a constructor:

public MyClass2(MyClass1 other)
{
    this.SomeProperty = other.SomeProperty;
    // etc
}

MyClass2 temp = new MyClass2((MyClass1)myObjectInput);


More likely, what you should do is make the projects share MyClass in a way that .NET understands and supports natively: by putting it in a project that can be referenced by both projects. If one project should reference the other, do that; otherwise, create a third project as a library.

这篇关于无法投C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆