小编The*_*l26的帖子

C#5中不提供"插值字符串"功能.请使用语言版本6或更高版本

还有一个类似的问题这在这里,但我相信,涉及不同的原因.

我把一个班级从一个较新的项目搬到了一个较旧的项目中.两者都针对.net 4.6然而在移动后我在构建时收到以下错误.

C#5中不提供"插值字符串"功能.请使用语言版本6或更高版本.

我尝试将项目设置为在属性窗口中使用C#6进行构建而不做任何更改.

c# c#-6.0 .net-4.6

16
推荐指数
4
解决办法
1万
查看次数

System.Timers.Timer在调用timer.Stop()之后执行Elapsed事件

背景:我有一个计时器,用于跟踪自触发serialPort DataReceived事件以来已经过了多长时间.我正在创建自己的解决方案,而不是使用内置的超时事件,因为我获得了连续的数据流,而不是发送查询并获得一个响应.

问题: 在DataReceived处理程序中,我有一个语句来停止计时器,以便不会过去.问题是很多时候它仍然执行Elapsed处理程序后跟.

我已经读过可以使用SynchronizingObject来解决这个问题,但我不知道如何实现.

这是我的代码:我试图删除我认为不相关的所有内容.

    private System.Timers.Timer timeOut;
    private System.Timers.Timer updateTimer;

    public void start()
    {
        thread1 = new Thread(() => record());

        thread1.Start();
    }

    public void requestStop()
    {
        this.stop = true;
        this.WaitEventTest.Set();

    }

    private void record()
    {
        timeOut = new System.Timers.Timer(500); //** .5 Sec
        updateTimer = new System.Timers.Timer(500); //** .5 Sec

        timeOut.Elapsed += TimeOut_Elapsed;
        updateTimer.Elapsed += updateTimer_Elapsed;
        updateTimer.AutoReset = true;


        comport.Open();
        comport.DiscardInBuffer();


        comport.Write(COMMAND_CONTINUOUSMODE + "\r");

        stopwatch.Reset();
        stopwatch.Start();

        recordingStartTrigger(); //** Fire Recording Started Event

        timeOut.Start();
        updateTimer.Start();

        this.waitHandleTest.WaitOne(); //** wait …
Run Code Online (Sandbox Code Playgroud)

.net c# timer

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

一个用于多项目解决方案的记录器

我正在将Serilog集成到我创建的现有多级层和多装配解决方案中.我之前使用的日志记录技术只是通过事件向字符串传递字符串.我想摆脱这个.

我已经读过,我可以使用app.config文件将记录器配置加载到我的库中的每个类中,但是如何在多组件项目中执行此操作.

我有一个顶级/启动项目和两个类库项目.我想在整个程序中使用带有两个接收器的相同记录器.

这些是我到目前为止发现的文章

https://github.com/serilog/serilog/wiki/AppSettings

http://nblumhardt.com/2014/04/xml-configuration-for-serilog/

有人可以解释如何实现这一目标吗?

serilog

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

无法从'void'转换为'System.Action'

将带参数的方法传递给接受Action类型参数的方法会导致语法错误

无法从'void'转换为'System.Action'

但是,如果我传递一个没有任何参数的方法,它可以正常工作.

我假设C#当我传递一个没有参数的方法时会自动执行某些操作.

我想知道它在幕后做了什么,以及如何使用带参数的方法做同样的事情.

public void Invoke(Action action){ /*Code Here */ }

public void Method1(){ /*Code Here */}

public void Method2(int param){ /*Code Here */ }

public void test()
{
    int testParam = 1;
    //** This works
    Invoke(Method1);
    //** This does not work
    Invoke(Method2(testParam));     
}
Run Code Online (Sandbox Code Playgroud)

c# action

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

找不到方法:'Serilog.LoggerConfiguration

我的解决方案有一个主记录器,它被定义为

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.LiterateConsole(LogEventLevel.Verbose)
        .WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log")
        .WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs-warnings{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log", LogEventLevel.Warning)
        .WriteTo.File($"{appLogDir}{Path.DirectorySeparatorChar}recent-log.log", fileSizeLimitBytes: 134217728, restrictedToMinimumLevel: LogEventLevel.Verbose)
        .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

我想创建两个单独的记录器来记录两个类实例中的内容。我已将它们定义如下。它位于与主项目不同的程序集中。

private ILogger comRespLog;
public **constructor**(string name)
{
comRespLog = new LoggerConfiguration()
                .MinimumLevel.Verbose()            
                .WriteTo.RollingFile($"{appLogDir}{Path.DirectorySeparatorChar}logs-CommandResponse-{Name}{Path.DirectorySeparatorChar}V-RPi-{{Date}}.log")
                .CreateLogger();
}
Run Code Online (Sandbox Code Playgroud)

我没有收到构建错误,但我在运行时收到了这个错误。

方法未找到:'Serilog.LoggerConfiguration Serilog.RollingFileLoggerConfigurationExtensions.RollingFile(Serilog.Configuration.LoggerSinkConfiguration, System.String, Serilog.Events.LogEventLevel, System.String, System.IFormatProvider, System.Nullable 1<Int64>, System.Nullable1, Serilog.Core.LoggingLevelSwitch, Boolean ,布尔值,System.Nullable`1)'。"}

c# serilog

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

将空值引用类型转换为非空值引用类型

在下面的示例中,有没有办法我可以将空值引用类型转换为非空值引用类型呢?

这将在启用编译器的可空引用标志时使用。

当可为空的引用类型为null时,我希望它引发异常。

    Assembly? EntryAssemblyNullable = Assembly.GetEntryAssembly();

    if (EntryAssemblyNullable is null)
    {
        throw new Exception("The CLR method of Assembly.GetEntryAssembly() returned null");
    }

    Assembly EntryAssembly = EntryAssemblyNullable;
    var LocationNullable = Path.GetDirectoryName(EntryAssembly.Location);
    if (LocationNullable is null)
    {
        throw new Exception("The CLR method of Assembly.GetEntryAssembly().Location returned null");
    }

    string ExecutableLocationPath = LocationNullable;
Run Code Online (Sandbox Code Playgroud)

c# c#-8.0

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

是否可以在程序的GUI中显示Serilog日志?

我正在替换我用Serilog自己编写的所有现有日志记录代码.我想知道是否可以在文本框,列表视图或其他GUI控件中显示日志.如果是这样的话?我的UI是WinForms.

目前,我正在使用滚动文件接收器.除此之外,我想这样做.

.net c# serilog

6
推荐指数
3
解决办法
2235
查看次数

如何从 TypeScript 中的日期减去天数

我想从 TypeScript 的当前日期中减去天数。例如,如果当前日期是 2017 年 10 月 1 日,我想减去 1 天得到 2017 年 9 月 30 日,或者如果我想减去 3 天我得到 9 月 28 日等。

这是我目前所拥有的,结果是我在 1969 年 12 月 31 日收到。我认为这意味着 tempDate.getDate() 返回零,就像在 1970 年 1 月 1 日的时代一样。

这是我的代码,目标是返回前一个工作日。

    protected generateLastWorkingDay(): Date {

        var tempDate = new Date(Date.now());
        var day = tempDate.getDay();


        //** if Monday, return Friday
        if (day == 1) {
            tempDate = new Date(tempDate.getDate() - 3);
        } else if (1 < day && day <= 6) {
            tempDate …
Run Code Online (Sandbox Code Playgroud)

datetime typescript

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

我如何使用 xUnit Assert.RaisesAny?

我如何使用 xUnit Assert.RaisesAny()?我似乎找不到任何例子。

我收到以下语法错误

事件 'IMqttServer.Started' 只能出现在 += 或 -= 的左侧

这是有道理的,因为我没有订阅它,但我不知道 RaisesAny() 使用什么语法

基本上,我只是想检查 Broker 是否启动,至少有 1 个客户端连接到它并且它停止了。

PS MqttServer 是 Mqtt Broker 实现,是MqttNet 的一部分

这是我的测试

public class ResearchTestingOnly
{

    private readonly ITestOutputHelper output;

    public ResearchTestingOnly(ITestOutputHelper output)
    {
        this.output = output;
    }


    [Fact]
    public void Test1()
    {

        IMqttServer _mqttBroker = new MqttFactory().CreateMqttServer();

        var receivedEvents = new List<string>();

        _mqttBroker.ClientConnected += delegate (object sender, MqttClientConnectedEventArgs args)
        {
            receivedEvents.Add(args.ClientId);
        };

        Assert.RaisesAny<EventHandler>(_mqttBroker.Started);

        Assert.RaisesAny<MqttClientConnectedEventArgs>(_mqttBroker.ClientConnected);

        Assert.RaisesAny<EventHandler>(_mqttBroker.Stopped);

        //** Start Broker
        Task _brokerTask = Task.Run(() …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing xunit

3
推荐指数
1
解决办法
998
查看次数

从类型为void的方法返回任务

我想创建一个运行串行命令的任务.这时我不需要从正在进行工作的方法中返回任何内容.这可能会在以后改变,但我现在很好奇这是怎么回事.

这就是我所拥有的.我想为该任务使用单独的方法,而不是创建匿名操作.我试过返回void,结果是"void无法显式转换为Task".我也试过了.Task<void>.我尝试过的最后一件事是返回一个任务,但我收到了,错误"并非所有代码路径都返回一个值"和"不能暗示将void转换为类型任务"

在此输入图像描述

在传递中我使用了一个Thread来完成这个,但是这次我想使用Tasks.

internal class Hardware
{
    private EventHandler<SequenceDoneEventArgs> SequenceDone;

    private List<Step> Steps;
    private System.IO.Ports.SerialPort comport = null;

    private Task SequenceTask;
    private CancellationTokenSource RequestStopSource;
    private CancellationToken RequestStopToken;


    private void Initialize()
    {
        comport = new System.IO.Ports.SerialPort("COM2", 115200, System.IO.Ports.Parity.None,8);
        comport.DataReceived += Comport_DataReceived;
    }

    public async void RunSequence()
    {
        if (comport == null)
        {
            Initialize();
        }
        if (!comport.IsOpen)
        {
            comport.Open();
        }

        RequestStopSource = new CancellationTokenSource();
        RequestStopToken = RequestStopSource.Token;

        SequenceTask = await Task.Run(() => { doSequence(); });

    }

    private Task doSequence()
    { …
Run Code Online (Sandbox Code Playgroud)

c# task

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

接受Func &lt;T&gt;的简单超时方法未在等待

我正在尝试创建一个简单的可重用的超时方法,该方法是完全异步的。由于某种原因,我的超时方法没有被等待,我为之感到困惑。

    [Fact]
    public async void TestTimeOut()
    {
        Stopwatch sw = Stopwatch.StartNew();
        var Thrown = false;
        try
        {
            await TimeOut(() => Task.Delay(5000), TimeSpan.FromMilliseconds(1000));
        }
        catch(OperationCanceledException ex)
        {
            //** Never Hit
            Thrown = true;
        }
        sw.Stop();

        Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1000)); //** fails nothing is awaited, executes in less than 40ms

        Assert.True(Thrown); //** Fails
    }

    private async Task<T> TimeOut<T>(Func<T> method, TimeSpan timeOut)
    {
        using (var ctsForTask = new CancellationTokenSource())
        {
            var taskTimeOut = Task.Delay(timeOut);
            Task<T> task = Task.Run(() => method(), ctsForTask.Token);
            if (task != …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous async-await

0
推荐指数
1
解决办法
56
查看次数

构造函数定义:接收"不给出参数"

我正在尝试创建一个派生类,我收到每个构造函数的语法错误.

没有给出的参数对应于'Parent.Parent(Parent)'所需的形式参数'p'

这对我没有任何意义.这是一个构造函数定义,而不是方法调用,我以前从未在非调用的东西上看到这个.

namespace ConsoleApp1
{

        public class Parent
        {
            public string Label;

            public Parent(Parent p)
            {
                Label = p.Label;
            }
        }

        public class Child : Parent
        {
            public string Label2;

            public Child(Parent p)
            {
                Label = p.Label;
            }

            public Child(Child c)
            {
                Label = c.Label;
                Label2 = c.Label2;
            }

            public Child(string blah, string blah2)
            {
                Label = blah;
            }
        }
    class Program
    {
        static void Main(string[] args)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

c# visual-studio-2017

-1
推荐指数
1
解决办法
124
查看次数

如何将短片转换为bool []?

如何在C#中将短片转换为布尔数组(bool [])?我正在寻找一种算法,多种选择将受益于它们的优点和缺点.

因此,例如,如果我有一个短的= 132,即二进制10000100

所以我想要一个{false,false,true,false,false,false,false,true}的数组

bool[] ToArrayOfBool(short source)
{
    bool[] result = new bool[16];

    ///Do Some stuff here


    return result;
}
Run Code Online (Sandbox Code Playgroud)

c#

-3
推荐指数
1
解决办法
102
查看次数