小编Jep*_*sen的帖子

在.NET中,如果null的哈希码始终为零

鉴于像System.Collections.Generic.HashSet<>accept 这样的集合null成为集合成员,可以询问哈希代码null应该是什么.它看起来像框架使用0:

// nullable struct type
int? i = null;
i.GetHashCode();  // gives 0
EqualityComparer<int?>.Default.GetHashCode(i);  // gives 0

// class type
CultureInfo c = null;
EqualityComparer<CultureInfo>.Default.GetHashCode(c);  // gives 0
Run Code Online (Sandbox Code Playgroud)

对于可以为空的枚举,这可能会(有点)出现问题.如果我们定义

enum Season
{
  Spring,
  Summer,
  Autumn,
  Winter,
}
Run Code Online (Sandbox Code Playgroud)

然后Nullable<Season>(也称为Season?)可以只取五个值,但其中两个,即nullSeason.Spring,具有相同的哈希码.

写这样一个"更好"的平等比较器是很诱人的:

class NewNullEnumEqComp<T> : EqualityComparer<T?> where T : struct
{
  public override bool Equals(T? x, T? y)
  {
    return Default.Equals(x, y);
  }
  public override int …
Run Code Online (Sandbox Code Playgroud)

.net c# hash null

85
推荐指数
3
解决办法
9146
查看次数

做短路运营商|| 和&&存在可空的布尔?RuntimeBinder有时会这么认为

我读上的C#语言规范条件逻辑运算符 ||&&,也被称为短路逻辑运算符.对我来说,似乎不清楚这些是否存在可空的布尔值,即操作数类型Nullable<bool>(也是书面的bool?),所以我尝试使用非动态类型:

bool a = true;
bool? b = null;
bool? xxxx = b || a;  // compile-time error, || can't be applied to these types
Run Code Online (Sandbox Code Playgroud)

这似乎解决了这个问题(我无法清楚地理解规范,但假设Visual C#编译器的实现是正确的,现在我知道).

但是,我也想尝试dynamic绑定.所以我尝试了这个:

static class Program
{
  static dynamic A
  {
    get
    {
      Console.WriteLine("'A' evaluated");
      return true;
    }
  }
  static dynamic B
  {
    get
    {
      Console.WriteLine("'B' evaluated");
      return null;
    }
  }

  static void Main()
  {
    dynamic x = A | B;
    Console.WriteLine((object)x);
    dynamic y …
Run Code Online (Sandbox Code Playgroud)

c# nullable short-circuiting logical-operators dynamictype

84
推荐指数
2
解决办法
3302
查看次数

从int中提升/可空转换的严重错误,允许从十进制转换

我认为这个问题会让我在Stack Overflow上立刻成名.

假设您有以下类型:

// represents a decimal number with at most two decimal places after the period
struct NumberFixedPoint2
{
    decimal number;

    // an integer has no fractional part; can convert to this type
    public static implicit operator NumberFixedPoint2(int integer)
    {
        return new NumberFixedPoint2 { number = integer };
    }

    // this type is a decimal number; can convert to System.Decimal
    public static implicit operator decimal(NumberFixedPoint2 nfp2)
    {
        return nfp2.number;
    }

    /* will add more nice members later */
} …
Run Code Online (Sandbox Code Playgroud)

.net c# nullable compiler-bug implicit-conversion

59
推荐指数
2
解决办法
2857
查看次数

当逆变导致模糊时,没有警告或错误(或运行时故障)

首先,请记住.NET StringIConvertibleICloneable.

现在,考虑以下非常简单的代码:

//contravariance "in"
interface ICanEat<in T> where T : class
{
  void Eat(T food);
}

class HungryWolf : ICanEat<ICloneable>, ICanEat<IConvertible>
{
  public void Eat(IConvertible convertibleFood)
  {
    Console.WriteLine("This wolf ate your CONVERTIBLE object!");
  }

  public void Eat(ICloneable cloneableFood)
  {
    Console.WriteLine("This wolf ate your CLONEABLE object!");
  }
}
Run Code Online (Sandbox Code Playgroud)

然后尝试以下(在某些方法中):

ICanEat<string> wolf = new HungryWolf();
wolf.Eat("sheep");
Run Code Online (Sandbox Code Playgroud)

当编译它时,没有编译器错误或警告.运行它时,看起来调用的方法取决于我的class声明中的接口列表的顺序HungryWolf.(尝试在逗号(,)分隔列表中交换两个接口.)

问题很简单:这不应该给出编译时警告(或者在运行时抛出)吗?

我可能不是第一个提出像这样的代码的人.我使用了界面的逆变,但你可以用界面的covarainace做一个完全类似的例子.事实上,Lippert先生很久以前就做过这样的事情.在他博客的评论中,几乎每个人都认为这应该是一个错误.然而他们默默地允许这样做. …

.net c# ambiguity contravariance undefined-behavior

43
推荐指数
2
解决办法
917
查看次数

.NET Framework中字符串比较中的错误

任何比较排序都要求基础订单运算符具有传递性反对称性.

在.NET中,某些字符串不是这样的:

static void CompareBug()
{
  string x = "\u002D\u30A2";  // or just "-?" if charset allows
  string y = "\u3042";        // or just "?" if charset allows

  Console.WriteLine(x.CompareTo(y));  // positive one
  Console.WriteLine(y.CompareTo(x));  // positive one
  Console.WriteLine(StringComparer.InvariantCulture.Compare(x, y));  // positive one
  Console.WriteLine(StringComparer.InvariantCulture.Compare(y, x));  // positive one

  var ja = StringComparer.Create(new CultureInfo("ja-JP", false), false);
  Console.WriteLine(ja.Compare(x, y));  // positive one
  Console.WriteLine(ja.Compare(y, x));  // positive one
}
Run Code Online (Sandbox Code Playgroud)

你看,x它严格地大于y,并且y严格地大于x.

因为 …

.net c# sorting string-comparison

42
推荐指数
2
解决办法
2612
查看次数

在.NET 4.5中更改了string.Empty(或System.String :: Empty)的行为

精简版:

C#代码

typeof(string).GetField("Empty").SetValue(null, "Hello world!");
Console.WriteLine(string.Empty);
Run Code Online (Sandbox Code Playgroud)

在编译和运行时,"Hello world!"在.NET 4.0及更早版本下提供输出,但""在.NET 4.5和.NET 4.5.1下提供.

如何像这样忽略对字段的写入,或者,谁重置该字段?

更长的版本:

我从来没有真正理解为什么string.Empty字段(也称为[mscorlib]System.String::Empty)不是const(aka.literal),请参阅" 为什么String.Empty不是常量? ".这意味着,例如,在C#中我们不能string.Empty在以下情况下使用:

  • switch表格中的陈述case string.Empty:
  • 作为可选参数的默认值,如 void M(string x = string.Empty) { }
  • 在应用属性时,例如 [SomeAttribute(string.Empty)]
  • 需要编译时常量的其他情况

这对于众所周知的"宗教战争"是否影响是否使用string.Empty"",请参阅" 在C#中,我应该使用string.Empty或String.Empty还是"来初始化字符串? ".

几年前,我Empty通过反射设置其他字符串实例来自娱自乐,看看BCL有多少部分由于它而开始表现奇怪.这是很多.并且Empty参考的变化似乎在应用程序的整个生命周期中持续存在.现在,有一天我试图重复那个小噱头,但后来使用的是.NET 4.5机器,我再也无法做到了.

(注意!如果您的计算机上安装了.NET 4.5,可能PowerShell仍然使用较旧版本的.NET,请尝试复制粘贴[String].GetField("Empty").SetValue($null, "Hello world!")到PowerShell中以查看更改此引用的一些效果.)

当我试图寻找原因时,我偶然发现了一个有趣的主题:" .NET 4.5 beta版本中FatalExecutionEngineError的原因是什么? ".在该问题的公认答案中,是否注意到通过版本4.0,System.String有一个静态构造函数.cctor,其中Empty设置了字段(在C#源中,当然可能只是一个字段初始化程序),而在4.5中没有静态构造函数存在.在这两个版本中,字段本身看起来都是一样的:

.field public …
Run Code Online (Sandbox Code Playgroud)

.net c# string readonly .net-4.5

40
推荐指数
2
解决办法
1506
查看次数

C#编译器是否使用const类型成员获取Color Color规则?

好的,所以C#语言规范在规则上有一个特殊的部分(旧版链接),Color Color其中一个成员及其类型具有相同的名称.着名的大师Eric Lippert 曾在博客上发表过这篇文章.

我在这里要问的问题在某种意义上(不是)与常量枚举中的线程循环定义中提出的完全相同.如果你愿意,你可以去推荐其他问题.

现在我的问题.考虑以下代码:

namespace N
{
    public enum Color
    {
        Green,
        Brown,
        Purple,
    }

    public class C1
    {
        public const Color Color = Color.Brown;  // error CS0110 - WHY? Compiler confused by Color Color?
    }
    public class C2
    {
        public static readonly Color Color = Color.Brown;  // fine
    }
    public class C3
    {
        public static Color Color = Color.Brown;  // fine
    }
    public class C4
    {
        public Color …
Run Code Online (Sandbox Code Playgroud)

c# language-lawyer member-access

37
推荐指数
2
解决办法
1334
查看次数

为什么默认字符串比较器无法保持传递一致性?

我知道之前已经注意到这个问题,或多或少简洁,但我仍然创建这个新线程,因为我在编写单元测试时再次遇到了这个问题.

默认的字符串比较(即文化相关的区分大小写的比较,我们得到有string.CompareTo(string),Comparer<string>.Default,StringComparer.CurrentCulture,string.Compare(string, string)等)违反及物当字符串包含连字符(或减号,我说的是普通的U + 002D字符).

这是一个简单的复制品:

static void Main()
{
  const string a = "fk-";
  const string b = "-fk";
  const string c = "Fk";

  Console.WriteLine(a.CompareTo(b));  // "-1"
  Console.WriteLine(b.CompareTo(c));  // "-1"
  Console.WriteLine(a.CompareTo(c));  // "1"

  var listX = new List<string> { a, b, c, };
  var listY = new List<string> { c, a, b, };
  var listZ = new List<string> { b, c, a, };
  listX.Sort();
  listY.Sort();
  listZ.Sort();
  Console.WriteLine(listX.SequenceEqual(listY));  // "False" …
Run Code Online (Sandbox Code Playgroud)

.net c# sorting string string-comparison

30
推荐指数
1
解决办法
1953
查看次数

无法将类型'System.Linq.IQueryable'隐式转换为'System.Collections.Generic.IList'

我有一个方法:

public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
    DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
    DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
    if (firstname == null && lastname != null)
    {
        IList<DzieckoAndOpiekun> resultV = from p in db.Dziecko
                      where lastname == p.Nazwisko
                      **select** new DzieckoAndOpiekun(
                     p.Imie,
                     p.Nazwisko,
                     p.Opiekun.Imie,
                     p.Opiekun.Nazwisko)
                  ;
        result.AddRange(resultV);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

和选定位置的错误:

错误1无法将类型'System.Linq.IQueryable <WcfService1.DzieckoAndOpiekun>'隐式转换为'System.Collections.Generic.IList <WcfService1.DzieckoAndOpiekun>'.存在显式转换(您是否错过了演员?)

任何想法如何解决我的问题?

.net c# linq linq-to-entities exception-handling

29
推荐指数
3
解决办法
10万
查看次数

什么时候在C#中使用没有语句的范围?

就在最近我发现你可以在C#中做到这一点:

{
    // google
    string url = "#";

    if ( value > 5 )
        url = "http://google.com";

    menu.Add( new MenuItem(url) );
}
{
    // cheese
    string url = "#"; // url has to be redefined again, 
                      // so it can't accidently leak into the new menu item

    if ( value > 45 )
        url = "http://cheese.com";

    menu.Add( new MenuItem(url) );
}
Run Code Online (Sandbox Code Playgroud)

而不是ie:

    string url = "#";

    // google
    if ( value > 5 )
        url = "http://google.com";

    menu.Add( new MenuItem(url) …
Run Code Online (Sandbox Code Playgroud)

c# syntax block

26
推荐指数
3
解决办法
1058
查看次数