简体   繁体   English

是否有 C# 速记将值转换为其方法的返回类型?

[英]Is there C# shorthand to cast a value to its method's return type?

Is there shorthand in C# for casting a value to its method's return type? C# 中是否有用于将值转换为其方法的返回类型的简写? For example, in this method, is there a shorthand way to cast the return value of GetInt's to its return type of 'int', instead of discretely typing out 'int'?例如,在这个方法中,有没有一种速记方法可以将 GetInt 的返回值转换为其返回类型“int”,而不是离散地输入“int”?

I know this is a really simple example, and many of you are going to say "it's easier to just put (int) there" but it would be really great syntactic sugar for some things I'm trying to do if this is possible.我知道这是一个非常简单的例子,你们中的许多人会说“把 (int) 放在那里更容易”,但如果可能的话,对于我正在尝试做的一些事情来说,这将是一个很好的语法糖。 It would be very similar to the 'default' keyword shorthand that already exists.它与已经存在的“默认”关键字速记非常相似。

// Return type of SomeFunc cannot be changed by me
object SomeFunc();

public int GetInt()
{
    object Value = SomeFunc();
    // I know "Value" should be of type "int" here.
    return ({ReturnType})Value;
}

Does such a feature exist?有这样的功能吗? None that I am aware of.没有我知道的。

Can you add such syntactic sugar somehow?你能以某种方式添加这样的语法糖吗? Probably yes , but none of the options are going to be simpler than an explicit cast.可能是的,但没有一个选项会比显式转换更简单。 You may lose some IDE features.您可能会失去一些 IDE 功能。 You'll probably go against good practices.您可能会 go 反对良好做法。 I imagine that things like Reflection, Decorators, dynamic types, switch expressions , etc may be of use here.我想像反射、装饰器、动态类型、开关表达式等可能在这里有用。

Implicit conversions?隐式转换? You can always use a derived class implicitly converted to any of its base class.您始终可以使用派生的 class 隐式转换为其任何基础 class。 Some helpful links - casting-and-type-conversions , user-defined-conversion-operators , type-testing-and-cast一些有用的链接 - cast-and-type-conversionsuser-defined-conversion-operatorstype-testing-and-cast

If you are sure that your object is castable safely, you can use alternate syntax which doesn't throw an exception , Value as int如果您确定您的 object 是可安全转换的,您可以使用不抛出异常的替代语法, Value as int

At the end of the day, none of this needs to be considered first, unless one has a use case where it could help them BIG TIME .归根结底,这些都不需要首先考虑,除非有一个可以帮助他们BIG TIME的用例。 Syntactic sugar is not even close to that use case IMO, especially for a statically typed language.语法糖甚至不接近那个用例 IMO,尤其是对于静态类型的语言。

I can think of using generics (it won't work with int, but will with custom type):我可以考虑使用 generics (它不适用于 int,但适用于自定义类型):

public class Foo { }

public static object Value = null;
public static T GetFoo<T>() where T : Foo
{
    return (T)Value;
}

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

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