小编use*_*514的帖子

在记录中定义属性两次

在 C# 9 中,可以在记录的主构造函数和主体中定义同名属性:

record Cat(int PawCount)
{
    public int PawCount { get; init; }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译没有错误。

初始化此类记录的实例时,提供给构造函数的值将被完全忽略:

Console.WriteLine(new Cat(4));
Console.WriteLine(new Cat(4) { PawCount = 1 });
Run Code Online (Sandbox Code Playgroud)

印刷

Cat { PawCount = 0 }
Cat { PawCount = 1 }
Run Code Online (Sandbox Code Playgroud)

这种行为是正确的还是错误?如果它是正确的,它在哪些情况下有用?

我希望编译器要么拒绝此代码,并显示“类型Cat已经包含PawCount'的定义”之类的错误,要么将构造函数中的属性和主体中的属性视为相同,从构造函数执行其初始化。后一种变体可用于为属性提供自定义 getter 和/或初始值设定项,而无需在其主体中重写位置记录的所有属性。

实际行为对我来说毫无意义。

c# c#-9.0

10
推荐指数
1
解决办法
282
查看次数

F#.元组与否

我刚开始学习F#.

我想知道如何确定函数的参数是否为元组?

let tuple = (1, 2)
let notTuple = 3

let isTuple t =  // returns 'true' if t is a tuple, 'false' otherwise

printfn "%b" isTuple tuple      // true
printfn "%b" isTuple notTuple   // false
Run Code Online (Sandbox Code Playgroud)

f# types tuples matching

9
推荐指数
2
解决办法
603
查看次数

IDictionary和IReadOnlyDictionary的扩展方法

我的问题类似于前一个问题,但这个问题的答案不适用于此问题.

好吧,我想为两者IDictionaryIReadOnlyDictionary接口编写扩展方法:

public static TValue? GetNullable<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
    where TValue : struct
{
    return dictionary.ContainsKey(key)
        ? (TValue?)dictionary[key]
        : null;
}

public static TValue? GetNullable<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
    where TValue : struct
{
    return dictionary.ContainsKey(key)
        ? (TValue?)dictionary[key]
        : null;
}
Run Code Online (Sandbox Code Playgroud)

但是当我将它用于实现两个接口的类(例如Dictionary<Tkey, TValue>)时,我得到了"模糊的调用".我不想打字var value = myDic.GetNullable<IReadOnlyDictionary<MyKeyType, MyValueType>>(key),我希望它只是var value = myDic.GetNullable(key).

这可能吗?

c# idictionary

7
推荐指数
2
解决办法
2204
查看次数

ICollection 和 IReadOnlyCollection 的扩展方法

我想.IsEmpty()为 ICollection 和 IReadonlyCollection 接口编写一个扩展方法(例如):

public static bool IsEmpty<T>(this IReadOnlyCollection<T> collection)
{
  return collection == null || collection.Count == 0;
}

public static bool IsEmpty<T>(this ICollection<T> collection)
{
  return collection == null || collection.Count == 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我将它与实现两个接口的类一起使用时,我显然得到了“模棱两可的调用”。我不想打字myList.IsEmpty<IReadOnlyCollection<myType>>(),我只想打字myList.IsEmpty()

这可能吗?

c# icollection

5
推荐指数
1
解决办法
1447
查看次数

标签 统计

c# ×3

c#-9.0 ×1

f# ×1

icollection ×1

idictionary ×1

matching ×1

tuples ×1

types ×1