小编Joh*_*ica的帖子

Thread.sleep代码(-1)

有什么用?

 System.Threading.Thread.Sleep(-1)
Run Code Online (Sandbox Code Playgroud)

我希望这会引发异常,因为Thread.Sleep的文档说明了这一点

timeout的值为负,不等于Timeout.Infinite(以毫秒为单位),或者大于Int32.MaxValue毫秒.

但是,上面的Thread.Sleep(-1)不会抛出异常.当我看到ReferenceSource时,我看到了

[System.Security.SecuritySafeCritical]  // auto-generated
public static void Sleep(int millisecondsTimeout)
{
    SleepInternal(millisecondsTimeout);
    // Ensure we don't return to app code when the pause is underway
    if(AppDomainPauseManager.IsPaused)
        AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
}

public static void Sleep(TimeSpan timeout)
{
    long tm = (long)timeout.TotalMilliseconds;
    if (tm < -1 || tm > (long) Int32.MaxValue)
        throw new  ArgumentOutOfRangeException("timeout",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
    Sleep((int)tm);
}
Run Code Online (Sandbox Code Playgroud)

看起来它不会在负时间范围内抛出,但只有负时间跨度小于-1.

确实如此

 Thread.Sleep(-2);
Run Code Online (Sandbox Code Playgroud)

确实会崩溃.

那么这里的特例是什么呢-1?什么是Thread.Sleep(-1)真正在做什么?

c# multithreading

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

将int和char分开并制作整数

大家好我写了一个简单的程序,将参数中的字符串拆分为数字,字母和运算符,但是我遇到了23x + 3 = 8

foreach (char x in args[i]){

    if (char.IsNumber(x)){
        inter[i] = Convert.ToInt32(x);
            Console.WriteLine("{0} is a number ", x);
    }
    else if (char.IsLetter(x)){
        apha[i] = x;
        Console.WriteLine("{0} is a Letter ", x);
    }
    else if (char.IsSymbol(x)){
        symbol[i] = x;
        Console.WriteLine("{0} is a Symbol ", x);
    }
Run Code Online (Sandbox Code Playgroud)

我发现输出是分开的每个char 2和3我想要23作为一个整数.有没有办法将2号码组合在一起?

c#

5
推荐指数
0
解决办法
131
查看次数

BaseClass与实例计数器

我有一个基类和几个派生类(例如BaseChildA : Base).每次我创建一个ChildA类的实例时,我希望它被分配一个唯一的实例编号(类似于关系数据库中的自动增量ID,但对于我在内存中的类而不是在数据库中).

我的问题类似于这个问题,但有一个明显的区别:我希望基类自动处理这个问题.对于我的每个派生类(ChildA,ChildB,ChildC等),我希望基类保持单独的计数,并在创建该派生类的新实例时增加它.

所以,我Base班上的信息可能最终看起来像这样:

ChildA,5
ChildB,6
ChildC,9
Run Code Online (Sandbox Code Playgroud)

如果我然后实例化一个新的ChildB(var instance = new ChildB();),我希望ChildB被赋予id 7,因为它从6开始.

然后,如果我实例化一个新的ChildA,我希望ChildA被分配id 6.

-

我怎样才能在Base班级的构造函数中处理这个问题?

c#

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

如何在新行中用特定元素替换多个 &lt;br/&gt; 标签?

我有一个包含多个<p>标签的 XML 文件。一些<p>标签包含<br/>在其中。所以,我应该为标签中的XElement每个创建一个新<br/>的。我试图通过使用读取每一行foreach并将每一行替换<br/></p> + Environment.NewLine + <p>.

它的工作原理,但如果<p>包含这样的标签<b><i>,然后<>成为&lt;&gt;分别。这就是为什么我想要一种linq方法或一种foreach方法,以便我能够以 XML 格式进行更改。

请帮忙。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE repub SYSTEM "C:\repub\Repub_V1.dtd">
<?xml-stylesheet href="C:\repub\repub.xsl" type="text/xsl"?>
<repub>
<head>
<title>xxx</title>
</head>
<body>
<sec>
<title>First Title</title>
<break name="1-1"/>
<pps>This is Sparta</pps>
<h1><page num="1"/>First Heading</h1>
<bl>This is another text</bl>
<fig><img src="images/img_1-1.jpg" alt=""/><fc>This is a …
Run Code Online (Sandbox Code Playgroud)

.net c# xml linq

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

InvalidOperationException:无法使用在抽象类上声明的构造函数编译 NewExpression

尝试从 mongodb 检索对象时出错:

InvalidOperationException:无法使用在抽象类上声明的构造函数编译 NewExpression

我的班级是:

public class App 
{
    public List<Feature> Features { get; set; }
}

public abstract class Feature
{
    public string Name { get; set; }
}

public class ConcreteFeature : Feature
{
    public string ConcreteProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

不知道为什么它有抽象问题。我明白了,mongodb 记录了_t: "ConcreteFeature"类型名称,它具有反序列化的所有功能。我在抽象类中没有构造函数。

想法?

.net c# mongodb .net-core mongodb-.net-driver

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

finally 块的隐藏函数?

当我看到这个(第 790-811 行)时,我正在阅读源代码:ConcurrentQueue

//We need do Interlocked.Increment and value/state update in a finally block to ensure that they run
//without interuption. This is to prevent anything from happening between them, and another dequeue
//thread maybe spinning forever to wait for m_state[] to be true;
try
{ }
finally
{
    newhigh = Interlocked.Increment(ref m_high);
    if (newhigh <= SEGMENT_SIZE - 1)
    {
        m_array[newhigh] = value;
        m_state[newhigh].m_value = true;
    }

    //if this thread takes up the last slot in the segment, …
Run Code Online (Sandbox Code Playgroud)

.net c# finally

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

如何检测后退按钮点击并使webview返回

我正在尝试使用 Xamarin 为我的一个项目构建一个 webview 应用程序,但我似乎无法弄清楚如何让 webview 元素转到上一页而不是关闭应用程序。

所以我想出了如何检测被按下的后退按钮并防止它关闭应用程序,但我想让网页返回,如果网页无法返回,则关闭应用程序。

这是我目前的代码:

using System;
using Xamarin.Forms; 
using Xamarin.Forms.Xaml; 
using Application = Xamarin.Forms.Application; 

namespace myNewApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public class WebPage : ContentPage
    {
        public object _browser { get; private set; }

        protected override bool OnBackButtonPressed()
        {

                base.OnBackButtonPressed();
                return true;

        }

        public WebPage()
        {


            var browser = new Xamarin.Forms.WebView();

            browser.Source = "https://myurl.com";


            Content = browser;

        }



    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几个答案,我发现了这段代码,但它不起作用,因为覆盖无法访问公共网页浏览器变量:

if (browser.CanGoBack)
            {
                browser.GoBack();
                return true;
            }
            else
            {
                base.OnBackButtonPressed();
                return true;
            }
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激。

c# android xamarin

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

无法转换lambda表达式(async/await)

无法将lambda表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型

我想在另一个线程中运行函数,我可以毫无错误地执行此操作,但仅在计算函数不是时void.我想使用void函数.请告诉我该怎么做或它应该返回什么样的结果?

private async void buttonStep3_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = folderBrowserDialog1.ShowDialog();
            if (dialogResult != DialogResult.OK)
                return;

            SetAllButtonsStateEnabled(false);

            progressBar1.Value = 0;
            progressBar1.Visible = true;

            var progressProgressBarValue = new Progress<int>(s => progressBar1.Value = s);

            await Task.Run(() => SizeFilter3(
                                    Convert.ToInt32(textBoxSF1W.Text), Convert.ToInt32(textBoxSF1H.Text),
                                    Convert.ToInt32(textBoxSF2W.Text), Convert.ToInt32(textBoxSF2H.Text),
                                    Convert.ToInt32(textBoxSF3W.Text), Convert.ToInt32(textBoxSF3H.Text),
                                    Convert.ToInt32(textBoxSF4W.Text), Convert.ToInt32(textBoxSF4H.Text),
                                    Convert.ToInt32(textBoxSF5W.Text), Convert.ToInt32(textBoxSF5H.Text),
                                    progressProgressBarValue),
                                TaskCreationOptions.LongRunning);//this line gives an error


            progressBar1.Visible = false;
            progressBar1.Value = 0;

            SetAllButtonsStateEnabled(true);
        }
private void SizeFilter3(int filterW1, int filterH1,
                                   int filterW2, int filterH2,
                                   int filterW3, int filterH3,
                                   int …
Run Code Online (Sandbox Code Playgroud)

c# async-await

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

如何获取当前使用的网络适配器

现在我正在尝试在我的机器上的多个网络适配器之间获取正在使用的网络适配器,以便我可以获得网络适配器的ip地址、mac地址和适配器名称。但我没有任何运气。我找到的解决方案是获取当前使用的网络适配器。我不认为它适用于 .Net 框架项目,而是适用于 ASP.NET Core。

我的代码如下。

public void GetIpAndMacAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces
        if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
            nic.OperationalStatus == OperationalStatus.Up)
        {
            IPInterfaceProperties adapterProperties = nic.GetIPProperties();
            foreach (var ip in adapterProperties.UnicastAddresses) 
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    IPAddress = ip.Address.ToString();
            }
            string hexMac = nic.GetPhysicalAddress().ToString(),
                   regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})",
                   replace = "$1:$2:$3:$4:$5:$6";
            IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

            netAdapterName = nic.Name;
            MACAddress = Regex.Replace(hexMac, regex, replace);
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

c# mac-address ip-address

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

如何在控制台窗口中将字符串设为粗体?

所以我试图找到一个简单的代码,使我的代码以粗体打印。当我在互联网上搜索时,所有这些都非常复杂,甚至不值得。有没有更简单的方法来制作字符串或只是一个 Console.WriteLine(" "); 胆大?

Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();
Run Code Online (Sandbox Code Playgroud)

c#

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