小编Pav*_*ski的帖子

Wpf中的StringFormat本地化问题

在WPF 3.5SP1中,我使用DataBindings中的最后一个功能StringFormat:

     <TextBlock Text="{Binding Path=Model.SelectedNoteBook.OriginalDate, StringFormat='f'}"
                FontSize="20" TextTrimming="CharacterEllipsis" />
Run Code Online (Sandbox Code Playgroud)

我面临的问题是日期总是用英文格式化...虽然我的系统是法语的?我如何强制日期遵循系统日期?

wpf datetime localization

109
推荐指数
7
解决办法
4万
查看次数

c# 8 switch 表达式:没有找到 switch 表达式的最佳类型

我在我的启动类(.net core 3.1)中添加了一个代码来返回基于参数的类型,我得到了编译时错误。

我在sharplab中创建了一个运行示例。如果 switch 表达式包含它运行良好的字符串或其他对象。

工作示例1:

var x = key switch
            {
                "myhandler1" => "something",
                "myhandler2" => "something else",
                _ => "default case"
            };
Run Code Online (Sandbox Code Playgroud)

工作示例2:

object obj =  s switch {
            "a" => new object(),
            "b" => new DateTime(),
            _ => throw new NotImplementedException()
        };
Run Code Online (Sandbox Code Playgroud)

错误示例:

interface IHandler { }
public class BaseHandler { }
public class MyHandler1: BaseHandler, IHandler { }
public class MyHandler2: BaseHandler, IHandler { }

class Program
{
    static void Main(string[] args) …
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core c#-8.0 switch-expression

14
推荐指数
1
解决办法
4608
查看次数

使用 EnumeratorCancellation 返回 AsyncEnumerable 或循环 WithCancellation 有什么区别

我有以下方法可以从 http 流中读取 csv 文档

public async IAsyncEnumerable<Line> GetLines([EnumeratorCancellation] CancellationToken cancellationToken)
{
    HttpResponseMessage response = GetResponse();

    using var responseStream = await response.Content.ReadAsStreamAsync();
    using var streamReader = new StreamReader(responseStream);
    using var csvReader = new CsvReader(streamReader);

    while (!cancellationToken.IsCancellationRequested && await csvReader.ReadAsync())
    {
        yield return csvReader.GetRecord<Line>();
    }
}
Run Code Online (Sandbox Code Playgroud)

以及其他地方使用结果的方法

var documentAsyncEnumerable = graphClient.GetLines(cancellationToken);
await foreach (var document in documentAsyncEnumerable.WithCancellation(cancellationToken))
{
    // Do something with document    
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我应该在一个地方使用取消令牌吗?应该在产生记录之前对取消令牌采取行动还是 IAsyncEnumerable.WithCancellation() 基本上做同样的事情?如果有的话有什么区别?

c# .net-core c#-8.0 iasyncenumerable

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

使用Linq的Where/Select过滤掉null并将类型转换为不可为空的方法不能做成扩展方法

假设我有

List<MyObject?> list = ...;
Run Code Online (Sandbox Code Playgroud)

我想把它变成List<MyObject>,但我无法删除可为空的引用。

下面是一个 MCVE。在我的项目中,我将可空引用警告转换为错误,因此下面注释掉的行将无法编译。

如果我这样做,.Where(e => e != null).Select(e => e!)那么在最新的 .NET Core 3.1.100 中就可以了,但是我无法将其提取到扩展方法中。

我尝试添加此扩展方法

    public static IEnumerable<T> NotNull<T>(this IEnumerable<T> enumerable)
    {
        return enumerable.Where(e => e != null).Select(e => e!);
    }
Run Code Online (Sandbox Code Playgroud)

但是它不会转换IEnumerable<MyObject?>IEnumerable<MyObject>,我不确定为什么。这导致我出现如下错误:

[CS8619] 类型“列表”的值中引用类型的可空性与目标类型“列表”不匹配。

有没有办法让NotNull上面的功能以某种方式工作?

c# linq c#-8.0 nullable-reference-types

11
推荐指数
3
解决办法
2800
查看次数

如何解释git日志中的括号?

运行git log给我这样的输出:

commit 69b6309f09365c09a2fe10f09aee801d1fae29ee (HEAD -> master, edeviserBranch)
Author: eDeviser <eDeviser@xyz.com>
Date:   Mon Sep 2 09:53:07 2019 +0200

    added foo

commit 59a08270fb730db259a8d5819bb585a613024d97 (origin/master, origin/HEAD)
Author: eDeviser <eDeviser@xyz.com>
Date:   Mon Sep 2 09:49:50 2019 +0200

    More Text
Run Code Online (Sandbox Code Playgroud)

我不明白括号内内容的含义。括号内的文字是什么意思?这是提交所基于的分支吗?HEAD -> master如果是,和origin/master之间有什么区别origin/HEAD

如何解释git日志中的括号?

git command-line

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

使用参数验证初始化可变不可空属性时避免 CS8618 警告

我有一个关于自 C# 8 以来可用的可为空引用类型系统的问题。

假设我们有一个带有可变引用类型属性的 C# 域模型类,如下所示:

public class Person
{

    public string Name { get; set; }

    public Person(string name)
    {         
        Name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止没有问题。但考虑现实世界的场景,我经常想检查属性的有效性,因为它是一个公共可变属性,我必须确保模型在属性更改时保持不变。

public class Person
{
    private string _name;

    public string Name
    {
        get => _name;
        set => _name = value ?? throw new ArgumentNullException("Name is required.");
    }


    public Person(string name)
    {         
        Name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后编译器生成CS8618警告,基本上是说

“不可为空的字段 _name 未初始化。考虑将该字段声明为可为空类型。”

因此,每次遇到警告时,我都必须用以下 pragma 指令将构造函数括起来。

#pragma warning disable CS8618
public Person(string name)
{ …
Run Code Online (Sandbox Code Playgroud)

c# c#-8.0 nullable-reference-types

9
推荐指数
5
解决办法
4057
查看次数

如何读取BenchmarkDotNet的结果表

我运行了一个基准示例并得到了这张表。

BenchmarkDotNet=v0.12.0, OS=Windows 7 SP1 (6.1.7601.0)
Intel Xeon CPU E5-4660 v3 2.10GHz, 1 CPU, 28 logical and 14 physical cores
Frequency=2050214 Hz, Resolution=487.7540 ns, Timer=TSC
  [Host]     : .NET Framework 4.8 (4.8.4018.0), X86 LegacyJIT  [AttachedDebugger]
  DefaultJob : .NET Framework 4.8 (4.8.4018.0), X86 LegacyJIT


| Method |      Mean |    Error |   StdDev |
|------- |----------:|---------:|---------:|
| Sha256 | 173.60 us | 3.466 us | 9.604 us |
|    Md5 |  29.95 us | 0.599 us | 1.709 us |
Run Code Online (Sandbox Code Playgroud)

嗯……怎么读? …

.net c# benchmarking benchmarkdotnet

8
推荐指数
1
解决办法
668
查看次数

.Net Core 3.1 Process.Start("www.website.com") 在 WPF 中不起作用

我在 WPF 应用程序中使用 .Net Core 3.1 框架。我有一个按钮事件,我试图在点击时重定向到 Instagram 网址。但它给了我以下错误。

抛出异常:System.Diagnostics.Process.dll 中的“System.ComponentModel.Win32Exception”。

private void Insta_Click(object sender, RoutedEventArgs e)
{
    try
    {
        string targetURL = "https://www.instagram.com/xyz/";
        Process.Start(targetURL);
    }
    catch
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

c# wpf process .net-core

8
推荐指数
1
解决办法
1399
查看次数

检查字典中key的值是否为null

我尝试使用字典,需要检查键的值(称为名称)是否为空,如果是,则使用一些默认字符串作为我的键的值,例如“未知”。

我知道我可以检查一个字符串,string.Length == 0但我的问题是我有一个对象作为值,并且我很难捕获它。

那是我的代码:

 IDictionary<string, object> parameters = new Dictionary<string, object>();
 string Name = de.Properties["Name"].Value.ToString(); //Name is sometimes empty and sometimes not
 parameters.Add("Name", Name);
Run Code Online (Sandbox Code Playgroud)

更新:

IDictionary<string, object> parameters = new Dictionary<string, object>();
string Name = de.Properties["Name"].Value.ToString();
 if (parameters.TryGetValue("Name", out var Name))
    {
      parameters.Add("Name", Name ?? "unknown");
    }
Run Code Online (Sandbox Code Playgroud)

.net c# string dictionary

8
推荐指数
2
解决办法
3万
查看次数

C#如何缩短多个If表达式

我有多个验证布尔属性,可以需要也可以不需要。如果需要它们,则需要对其进行检查以进行验证。因此我不得不构建多个 if 语句来处理每个属性。我的问题是是否有更好的方法来维护这一点,而不必为每个新属性编写 if。

public class ProductionNavbarViewModel
{
    public bool IsProductionActive { get; set; }
    public bool ValidatedComponents { get; set; }
    public bool ValidatedGeometries { get; set; }
    public bool ValidatedPokayokes { get; set; }
    public bool ValidatedTechnicalFile { get; set; }
    public bool ValidatedStandardOperationSheet { get; set; }
    public bool ValidatedOperationMethod { get; set; }
    public bool IsComponentsRequired { get; set; }
    public bool IsGeometriesRequired { get; set; }
    public bool IsPokayokesRequired { get; set; }
    public bool …
Run Code Online (Sandbox Code Playgroud)

c# if-statement asp.net-core

8
推荐指数
4
解决办法
361
查看次数