小编Mat*_*mas的帖子

.Net Core - 复制到剪贴板?

是否可以使用.Net Core(以平台无关的方式)将某些内容复制到剪贴板?

似乎Clipboard缺少类,并且P/Invoking不是Windows之外的选项.

c# clipboard .net-core

20
推荐指数
2
解决办法
8540
查看次数

具有收益率返回的异步任务<IEnumerable>?

以下方法无法编译.备择方案?

public static async Task<IEnumerable<object[]>> GetRecordsAsync(
    this Transaction transaction,
    string commandText,
    params SqlParameter[] parameters)
{
    // Get a SqlDataReader
    var reader = await transaction.GetReaderAsync(commandText, parameters);
    var fieldCount = -1;
    // Begin iterating through records asynchronously
    while (await reader.ReadAsync()) // Note we don't loop until .ReadAsync returns a boolean
    {
        // Grab all the field values out
        if (fieldCount < 0)
            fieldCount = reader.FieldCount;
        var fields = new object[fieldCount];
        reader.GetValues(fields);
        // Yield return the field values from this record
        yield return …
Run Code Online (Sandbox Code Playgroud)

c# async-await

17
推荐指数
2
解决办法
7581
查看次数

可以转换为未继承的接口吗?

为什么不能投射一个实例:

sealed class Foo
{
    public void Go() { }
}
Run Code Online (Sandbox Code Playgroud)

...到这个界面:

interface IBar
{
    void Go();
}
Run Code Online (Sandbox Code Playgroud)

......即使Foo有签名IBar

如何将实例Foo转换为IBar?假设我无法控制Foo.

c#

12
推荐指数
1
解决办法
481
查看次数

为什么我的异步方法构建器必须是类或在调试模式下运行?

我正在尝试为自定义可等待类型实现我自己的异步方法构建器。我的可等待类型只是一个包含ValueTask<T>.

问题是我的异步方法生成器仅class在调试模式下编译时才起作用,而不是struct在发布模式下编译时才起作用。

这是一个最小的、可重现的示例。您必须将此代码复制到本地 PC 上的新控制台项目中,并在发布模式下运行它;.NET Fiddle 显然在调试模式下运行片段。当然,这需要 .Net 5+: https: //dotnetfiddle.net/S6F9Hd

CustomAwaitableAsyncMethodBuilder<T>当该代码是类或在调试模式下编译时,该代码会成功完成。但它会挂起并且无法完成,否则:

class Program
{
    static async Task Main()
    {
        var expected = Guid.NewGuid().ToString();
        async CustomAwaitable<string> GetValueAsync()
        {
            await Task.Yield();
            return expected;
        }

        var actual = await GetValueAsync();

        if (!ReferenceEquals(expected, actual))
            throw new Exception();

        Console.WriteLine("Done!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的自定义等待类型:

[AsyncMethodBuilder(typeof(CustomAwaitableAsyncMethodBuilder<>))]
public readonly struct CustomAwaitable<T>
{
    readonly ValueTask<T> _valueTask;

    public CustomAwaitable(ValueTask<T> valueTask)
    {
        _valueTask = valueTask;
    }

    public ValueTaskAwaiter<T> GetAwaiter() => _valueTask.GetAwaiter();
} …
Run Code Online (Sandbox Code Playgroud)

c# async-await

11
推荐指数
1
解决办法
1693
查看次数

ASP.Net Core Web API基于约定的路由?

我错过了什么,我受到了404这个控制器的欢迎?我真的不想使用基于属性的路由.我也不想action成为任何URI的一部分.

我正在使用Visual Studio 2017和.Net Core 1.1.

TestController.cs

using System;
using Microsoft.AspNetCore.Mvc;

namespace Foo.Controllers
{
    public class TestController : Controller
    {
        public long Get() => DateTimeOffset.Now.ToUnixTimeSeconds();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于[Route("api/Test")]属性.但我不想使用基于属性的路由.一旦我取消该属性,我就会得到404.

Startup.cs

namespace Foo
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core asp.net-core-webapi asp.net-core-routing

9
推荐指数
1
解决办法
4504
查看次数

将参数传递给dotnet测试项目?

我在Visual Studio 2017中的.Net Core 1.1单元测试项目(不是xUnit测试项目)中有以下测试类.如何将命令行参数传递给TestMethod

[TestClass]
public class TestClass
{
    [TestMethod]
    public void TestMethod()
    {
        var args = Environment.GetCommandLineArgs();
        var json = JsonConvert.SerializeObject(args);
        throw new Exception(json);
    }
}
Run Code Online (Sandbox Code Playgroud)

互联网上的很多地方听起来好像你可以把--你想要传递的参数放在前面,但我无法让它发挥作用.

这些是我尝试过的命令:

  • dotnet test TestProject.csproj -- hello=world
  • dotnet test TestProject.csproj -- --hello world
  • dotnet test TestProject.csproj -- -hello world

但是他们每次都输出这个消息.注意既不存在hello也不world存在:

[ "C:\用户\ ____ \的NuGet \包\ microsoft.testplatform.testhost\15.0.0\lib中\netstandard1.5\testhost.dll", " - 端口", "55032", " - parentprocessid" "24440"]

第一个字符串只是正在运行的程序集的名称 - 第一个命令行参数的标准.我不知道这些--port--parentprocessid论据的来源.

此外,这些变化使得dotnet …

c# integration-testing automated-tests .net-core

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

将拥有的数组分成拥有的两半

我想将一个拥有的数组分成两个拥有的一半\xe2\x80\x94两个单独的数组,而不是原始数组的切片。各自的大小是编译时间常数。有没有办法在不复制/克隆元素的情况下做到这一点?

\n
let array: [u8; 4] = [0, 1, 2, 3];\n\nlet chunk_0: [u8; 2] = ???;\nlet chunk_1: [u8; 2] = ???;\n\nassert_eq!(\n  [0, 1],\n  chunk_0\n);\nassert_eq!(\n  [2, 3],\n  chunk_1\n);\n
Run Code Online (Sandbox Code Playgroud)\n

因为这相当于仅仅移动元素的所有权,所以我有一种预感,应该对此有一个零成本的抽象。我想知道我是否可以通过巧妙地使用transmute和来做这样的事情forget。但这些功能的文档中有很多可怕的警告。

\n

我的主要动机是在内存中的大型数组上进行操作,而不需要太多的内存副本。例如:

\n
let raw = [0u8; 1024 * 1024];\n\nlet a = u128::from_be_array(???); // Take the first 16 bytes\nlet b = u64::from_le_array(???); // Take the next 8 bytes\nlet c = ...\n
Run Code Online (Sandbox Code Playgroud)\n

我知道实现上述模式的唯一方法是进行大量内存复制,这是多余的。

\n

arrays rust

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

字符串插值中的可变对齐组件

本例中的对齐组件是:-20

$"{value, -20}"

有没有办法制作这样的内插字符串:

$"{value, alignment}"

alignment变量在哪里?

c# string string-interpolation

7
推荐指数
1
解决办法
1189
查看次数

如何取消 Stream.ReadAsync?

如果您不输入任何输入,为什么下面的代码永远不会完成,为什么即使在取消标记被取消后它仍然响应按下的键?

// Set up a cancellation token
var cancellationSource = new CancellationTokenSource();

// Cancel the cancellation token after a little bit of time
Task.Run(async () =>
{
    await Task.Delay(TimeSpan.FromSeconds(2));
    cancellationSource.Cancel();
    Console.WriteLine("Canceled the cancellation token");
});

// Wait for user input, or the cancellation token
Task.Run(async () =>
{
    try
    {
        using (var input = Console.OpenStandardInput())
        {
            var buffer = new byte[1];
            Console.WriteLine("Waiting for input");
            await input.ReadAsync(buffer, 0, 1, cancellationSource.Token); // This is impossible to cancel???
            Console.WriteLine("Done waiting for input"); // …
Run Code Online (Sandbox Code Playgroud)

c# cancellation async-await c#-4.0

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

如何创建使用“in”而不是“ref”参数的“MemoryMarshal.CreateReadOnlySpan”方法?

MemoryMarshal.CreateReadOnlySpan有这个签名:

public static ReadOnlySpan<T> CreateReadOnlySpan<T> (ref T reference, int length);
Run Code Online (Sandbox Code Playgroud)

请注意,它需要一个ref参数。换句话说,你不能用它来执行此操作:

[StructLayout(LayoutKind.Sequential, Size = 512)]
struct LargeStruct
{}

class Program
{
    static readonly LargeStruct Blob = default;
    
    static byte GetSomethingFrom(in LargeStruct blob)
    {
        ReadOnlySpan<byte> span = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(in blob, 1));
        //                                                                               ^^^^^^^ Argument is 'in' while parameter is declared as 'ref'
        return span[5];
    }

    static void Main()
    {
        Console.WriteLine(GetSomethingFrom(in Blob));
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,我不能接受 a,ref因为Blob它是只读字段。

所以我只能做这样的事情:

[StructLayout(LayoutKind.Sequential, Size = 512)]
struct LargeStruct
{}

class Program …
Run Code Online (Sandbox Code Playgroud)

c#

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