繁体   English   中英

如何在一行代码中强制转换对象并调用函数?

[英]How can I cast an object in one line of code and call a function?

在C#中,如何将对象强制转换为另一种对象类型,以便可以调用仅强制转换对象具有的函数? 我想用一行代码来做到这一点。

这是我的代码,在其中创建强制类型的新对象:

if (_attributes[i] is DynamicPropertyAttribute)
{
    var attribute = _attributes[i] as DynamicPropertyAttribute;
    attribute.Compile();
}

我正在尝试在一行代码中完成上述操作。

这是我所拥有的:

if (_attributes[i] is DynamicPropertyAttribute)
{
    (DynamicPropertyAttribute)_attributes[i].Compile();
}

这是错误:

'System.Attribute'不包含'Compile'的定义,并且找不到扩展方法'Compile'接受类型为'System.Attribute'的第一个参数

将支架包裹在石膏上。

((DynamicPropertyAttribute)_attributes[i]).Compile();

如果您使用的是c#6,则可以使用“?。”运算符(有时也称为“安全导航运算符”)来简化它。

//no need for the if check anymore

(_attributes[i] as DynamicPropertyAttribute)?.Compile();

您可以使用以下命令在1行中强制转换并调用该函数:

if (_attributes[i] is DynamicPropertyAttribute)
{
    (_attributes[i] as DynamicPropertyAttribute).Compile();
}

但是,如果您使用的是C#6.0,则可以使用Null条件运算符?. 并避免使用显式的null检查,从而使代码更易于阅读。

(_attributes[i] as DynamicPropertyAttribute)?.Compile();

来自MSDN https://msdn.microsoft.com/zh-cn/library/dn986595.aspx的示例:

int? length = customers?.Length; // null if customers is null 
Customer first = customers?[0];  // null if customers is null
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM