C#,如何将对象转换为类类型
我正在开发 .NET CORE 应用程序。我已经声明了一个 Object
,我需要将其转换或转换为 Customer
类类型。我有一个场景,基于 bool 值,我需要更改类型并返回该类型。
错误
System.InvalidCastException: 'Object must implement IConvertible
客户类
public class Customer
{
public string Name { get; set; }
public Customer GetCutsomer(){
//
}
}
“对象转换”
public class MyService
{
public void CastType(){
Customer obj = new Customer();
var cus = GetCutsomer();
Object customer = new Object();
Convert.ChangeType(customer , cus.GetType());
}
}
I am working on .NET CORE application. I have declare an Object
that I need to cast or convert to Customer
class type. I have scenario where based on bool value I need to change the type and return that.
error
System.InvalidCastException: 'Object must implement IConvertible
Customer Class
public class Customer
{
public string Name { get; set; }
public Customer GetCutsomer(){
//
}
}
'Object Casting`
public class MyService
{
public void CastType(){
Customer obj = new Customer();
var cus = GetCutsomer();
Object customer = new Object();
Convert.ChangeType(customer , cus.GetType());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有一些选择。让我们创建一个 Customer 并通过分配给一个对象变量来释放这个事实。也不是客户来显示这种情况
,所以现在我们想找回其“客户”性
首先我们可以使用
as
null
因为 o2 不是 Customer 对象或者我们可以进行强制转换,
我们还可以使用
is
询问该对象这也有效(回答问题在评论中)
现在
然后稍后
即对象指针可以指向任何对象。
这就是继承的作用。 C# 中的所有类对象最终都派生自 Object,只是您在代码中看不到它。所以对象指针可以指向任何类对象
You have some choices. Lets make a Customer and loose that fact by assigning to an object variable. And one that isnt a customer to show that case too
so now we want to get back its 'customer'ness
First we can use
as
null
since o2 is not a Customer objectOr we can do a cast
We can also ask about the object using
is
This works too (answering question in comment)
now
then later
Ie an Object pointer can point at any object.
This is inheritance at work. All class objects in c# are ultimately derived from Object, you just dont see it in your code. So an Object pointer can point at any class object
您应该能够安全地将任何对象转换为类:
You should simply be able to safely cast any object to a class: