为什么我可以将 1 作为短变量传递,而不是 int 变量 i?

Why can I pass 1 as a short, but not the int variable i?(为什么我可以将 1 作为短变量传递,而不是 int 变量 i?)
本文介绍了为什么我可以将 1 作为短变量传递,而不是 int 变量 i?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个和第二个 Write 可以工作,而最后一个不行?有没有一种方法可以允许所有 3 个并检测它是 1、(int)1 还是我传入的?真的为什么允许一个但最后一个?第二个被允许但不是最后一个真的让我大吃一惊.

Why does the first and second Write work but not the last? Is there a way I can allow all 3 of them and detect if it was 1, (int)1 or i passed in? And really why is one allowed but the last? The second being allowed but not the last really blows my mind.

演示编译错误

using System;
class Program
{
    public static void Write(short v) { }
    static void Main(string[] args)
    {
        Write(1);//ok
        Write((int)1);//ok
        int i=1;
        Write(i);//error!?
    }
}

推荐答案

前两个是常量表达式,最后一个不是.

The first two are constant expressions, the last one isn't.

C# 规范允许将常量从 int 隐式转换为 short,但不允许其他表达式.这是一个合理的规则,因为对于常量,编译器可以确保值适合目标类型,但对于普通表达式则不能.

The C# specification allows an implicit conversion from int to short for constants, but not for other expressions. This is a reasonable rule, since for constants the compiler can ensure that the value fits into the target type, but it can't for normal expressions.

这条规则符合隐式转换应该是无损的准则.

This rule is in line with the guideline that implicit conversions should be lossless.

6.1.8 隐式常量表达式转换

隐式常量表达式转换允许以下转换:

An implicit constant expression conversion permits the following conversions:

  • int 类型的 constant-expression(第 7.18 节)可以转换为 sbytebyte 类型、shortushortuintulong,提供 constant-expression<的值/em> 在目标类型的范围内.
  • 只要 constant-expression 不是负数.
  • A constant-expression (§7.18) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.
  • A constant-expression of type long can be converted to type ulong, provided the value of the constant-expression is not negative.

(引自 C# 语言规范 3.0 版)

(Quoted from C# Language Specification Version 3.0)

这篇关于为什么我可以将 1 作为短变量传递,而不是 int 变量 i?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)