RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-237006

Vipz's questions

Martin Hope
Xzizz
Asked: 2025-03-16 00:08:44 +0000 UTC

如果我没有做任何改变,我应该完成交易吗?

  • 5

如果我没有做任何改变,我应该完成交易吗?

await using var transaction = await context.Database.BeginTransactionAsync();

var items = await context.Items.OrderBy(i => i.Id).Take(100).ToListAsync();

if (items.Count == 0)
{
    await transaction.CommitAsync();
    return false;
}

...

如果我只是保留该方法,会有什么危害吗?或者我应该使用await transaction.CommitAsync();?

任务是在一次交易中接收最多 100 个项目,更改它们,将它们保存到另一个位置,并删除从源收到的项目。

如果有 0 个项目,则不执行任何操作。

c#
  • 1 个回答
  • 46 Views
Martin Hope
Xzizz
Asked: 2024-10-11 15:18:08 +0000 UTC

我正在寻找一种发送数据的模式

  • 5

UPD:我试图重新表述它,因为有 2 票支持“关闭”

请建议类似这样的模式。

您需要将其写入2个不同的表,甚至写入2个不同的数据库。如果在第二种情况下没有发生记录,则回滚所有内容并返回错误。

它要么记录一切,要么什么也不记录。

public async Task SendAsync(IDefinerResult definerResult) 
{
    if (definerResult.DefinedLinks.Count != 0)
    {
        await definedLinkDAL.InsertAsync(definerResult.DefinedLinks);
    }

    if (definerResult.NotDefinedLinks.Count != 0)
    {
        await notDefinedLinkDAL.InsertAsync(definerResult.NotDefinedLinks);
    }
}
c#
  • 1 个回答
  • 51 Views
Martin Hope
Xzizz
Asked: 2024-10-05 17:02:00 +0000 UTC

如何在集合中使用泛型类?

  • 4

该类具有这样的依赖关系。

private readonly IDataReceiver<A> _receiverA;
private readonly IDataReceiver<B> _receiverB;

不同类型/不同数据库

我想将它们放在一个集合中,以便类构造函数具有更少的参数,但在这种情况下,发生了完全可怕的事情,并且通常不清楚类需要什么),如下所示:

private readonly Dictionary<Type, object> _receivers;

及用法:

var receiverA = new MockReceiver<A>();
var receiverB = new MockReceiver<B>();

var receivers = new Dictionary<Type, object>
{
    { typeof(A), receiverA },
    { typeof(B), receiverB }
};

我尝试了不同的方法,但一切仍然objeсt有效,语法方法是什么?

c#
  • 1 个回答
  • 53 Views
Martin Hope
Xzizz
Asked: 2024-10-04 17:02:34 +0000 UTC

什么不能 try/catch catch 以及如何处理?

  • 6

什么是它抓不到的try/catch?

如果他不能,也许其他东西可以?

我有以下问题:System.Private.CoreLib.dll 中类型为“System.AggregateException”的未处理异常

try/catch虽然在我看来他已经捕捉到了一切,但在这里不起作用……

我曾经问过关于这种行为的问题,但这还不够StackTrace,他们让我相信我нехорошее слово忘记在某个地方使用它await,这就是为什么一切都失败了,因为AggregareExeption

直到今天,我还以为我有一个门框,但我根本找不到,我通过重新启动应用程序来解决它。

即使是这样的错误,你又如何处理呢?

该库 99.9% 的工作正常,如果发生问题,我希望只需重新启动使用具有类似严重错误的库的组件。

在此输入图像描述

c#
  • 1 个回答
  • 90 Views
Martin Hope
Xzizz
Asked: 2024-10-04 13:53:23 +0000 UTC

System.Private.CoreLib.dll 中未处理的“System.AggregateException”类型异常

  • 5

如何处理这个异常呢?我的catch没捕捉到)

我用MySQL.Data

与一切相互作用的一切都MySQL.Data在try,没有任何缺失await。

但是,应用程序仍然会由于System.AggregateException.

Необработанное исключение типа "System.AggregateException" в System.Private.CoreLib.dll
One or more errors occurred.

    System.AggregateException
      HResult=0x80131500
      Сообщение = One or more errors occurred. (Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.)
      Источник = System.Private.CoreLib
      Трассировка стека:
       в System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs:строка 724
       в System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs:строка 669
       в System.Threading.TimerQueue.FireNextTimers() в /_/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs:строка 331
       в System.Threading.ThreadPoolWorkQueue.Dispatch() в /_/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs:строка 924
       в System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart() в /_/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WorkerThread.cs:строка 77
    
    Внутреннее исключение 1:
    MySqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    
    Внутреннее исключение 2:
    TimeoutException: The operation has timed out.

在 InnerExeptions[0].StackTrace 中:

   в MySql.Data.Common.StreamCreator.<>c.<GetTcpStreamAsync>b__8_1()
   в System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs:строка 977
   в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs:строка 179
--- Конец трассировки стека из предыдущего расположения ---
   в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs:строка 203
   в System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException) в /_/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs:строка 806

在此输入图像描述

UPD

我无法提供我的用例。

但即使在如此简单的构造中也不会捕获异常:

    while (true) 
    {
        try
        {
            using MySqlConnection? _mySqlConnection = new MySqlConnection
            {
                ConnectionString = connectionStringBuilder.ToString()
            };
            await _mySqlConnection.OpenAsync();
        }
        catch (AggregateException ae) 
        {
            foreach (Exception exception in ae.InnerExceptions)
            {
                Debug.WriteLine(exception);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        await Task.Delay(1000);
    }

UPD

我切换到 MySqlConnector - 我不必对代码进行任何更改,航班正常。

c#
  • 1 个回答
  • 58 Views
Martin Hope
Xzizz
Asked: 2024-02-22 16:33:29 +0000 UTC

序列化具有较少属性的对象

  • 5

有一个抽象类的对象列表。我无法更改此类本身,因为它属于 Nuget 的包。该类有 10 个属性。

我想序列化此列表,例如使用JsonSerializer字符串,但保存具有 10 个属性中的 3 个属性的对象。

我知道我可以通过使用某种迷你类创建一个列表来迭代这个列表,然后将其序列化。

还有更优雅的选择吗?

例如(创建 GPT):

public abstract class CarBase
{
    public abstract bool IsAvailable { get; }

    public virtual bool IsElectric => false;

    public bool IsLuxury => !IsAvailable;

    public virtual string Manufacturer { get; }

    public virtual int Year { get; }

    public virtual string Model { get; }

    public virtual string Color { get; }

    public virtual double EngineSize { get; }

    public virtual int NumberOfDoors { get; }

    public virtual string VIN { get; }

    public abstract string LicensePlate { get; }
}

并序列化,例如仅 3 个属性 Year / Model / Color

我不能忽略这个特定类中的某些属性 - 因为它是第三方库。

c#
  • 2 个回答
  • 56 Views
Martin Hope
Xzizz
Asked: 2023-08-16 00:05:30 +0000 UTC

写入时文件损坏

  • 5

覆盖文件(例如 .json)时会发生什么情况从而损坏它吗?

  • 当某个组件出现故障时。
  • 录音期间关闭电脑时
  • 还有别的东西

如果是,如何避免?

c#
  • 1 个回答
  • 57 Views
Martin Hope
Xzizz
Asked: 2023-07-28 23:54:27 +0000 UTC

比较 List<T> 的数据相等性

  • 6

我需要比较两个List<Car>数据的相等性。

我用谷歌搜索并找到了合适的方法SequenceEqual

看来我所做的一切都是MSDN上的

但如果类中Car存在对象Radio,则比较失败。

我的课程:

    public class Car : IEquatable<Car>
    {
        public string? Model { get; set; }
        public bool Dead { get; set; }
        public int MaxSpeed { get; set; }
        public Radio? Music { get; set; }

        public bool Equals(Car? other)
        {
            if (other == null)
                return false;

            return Model == other.Model &&
                    Dead == other.Dead &&
                    MaxSpeed == other.MaxSpeed &&
                    Music == other.Music;

        }

        public override bool Equals(object? obj) => Equals(obj as Car);
        public override int GetHashCode() => (Model, Dead, MaxSpeed, Music).GetHashCode();
    }

    public class Radio : IEquatable<Radio>
    {
        public int Volume { get; set; }

        public bool Equals(Radio? other)
        {
            if (other == null) 
            {
                return false;
            }

            return Volume == other.Volume;
        }

        public override bool Equals(object? obj) => Equals(obj as Radio);
        public override int GetHashCode() => (Volume).GetHashCode();
    }

未通过测试

[TestMethod]
public void CarTest_Equal_True()
{
    // Arrange
    List<Car> cars1 = new()
    {
        new Car()
        {
            Dead = false,
            MaxSpeed = 100,
            Model = "Tesla",
            Music = new Radio()
            {
                Volume = 100
            }
        }
    };

    List<Car> cars2 = new()
    {
        new Car()
        {
            Dead = false,
            MaxSpeed = 100,
            Model = "Tesla",
            Music = new Radio()
            {
                Volume = 100
            }
        }
    };

    // Act
    bool equal = cars1.SequenceEqual(cars2);

    // Assert
    Assert.AreEqual(true, equal);
}

通过测试

[TestMethod]
public void CarTest_MusicNull_Equal_True()
{
    // Arrange
    List<Car> cars1 = new()
    {
        new Car()
        {
            Dead = false,
            MaxSpeed = 100,
            Model = "Tesla"
        }
    };

    List<Car> cars2 = new()
    {
        new Car()
        {
            Dead = false,
            MaxSpeed = 100,
            Model = "Tesla"
        }
    };

    // Act
    bool equal = cars1.SequenceEqual(cars2);

    // Assert
    Assert.AreEqual(true, equal);
}

截图来自MSDN 在此输入图像描述

c#
  • 1 个回答
  • 48 Views
Martin Hope
Xzizz
Asked: 2023-07-25 21:25:39 +0000 UTC

服务、微服务、控制器——什么是什么?

  • 6

我经常看到服务、微服务、控制器、存储库等词。

它是什么?在哪里解释的?他们在哪些书中写到了它?

  • 这适用于建筑吗?去哪里看?
c#
  • 1 个回答
  • 85 Views
Martin Hope
Xzizz
Asked: 2023-07-01 23:35:32 +0000 UTC

等待数据

  • 6

该模型有授权方法

它包含登录名、密码和短信中的另一个代码

这里,在该方法的执行中,您需要接收来自用户的短信代码。

while我通常通过延迟轮询属性来愚蠢地完成所有等待

public string SmsCode { get; set;}

while(SmsCode == null)
{
    await Task.Delay(500);
}

你还能怎样做得更好?

c#
  • 1 个回答
  • 33 Views
Martin Hope
Xzizz
Asked: 2023-06-21 06:38:27 +0000 UTC

Task.Factory.StartNew - 等待并返回结果

  • 5

如何启动一堆后台线程并等待第一个线程返回结果?

在 Google 之后,我尝试了这个方法以及其他十几种方法,包括不使用 lambda。

Task task = Task.Factory.StartNew(async () =>
{
    AnalyseInfo analyseInfo = await myAnalyzer.AnalyseAsync();
    _analyseInfos.Add(analyseInfo);
});


Task<AnalyseInfo> task = Task<AnalyseInfo>.Factory.StartNew(async () =>
{
    return await myAnalyzer.AnalyseAsync();
});


Task<Task<AnalyseInfo>> task = Task<Task<AnalyseInfo>>.Factory.StartNew(async () =>
{
    return await myAnalyzer.AnalyseAsync();
});

但没能得到想要的结果。

我想使用等待任何完成的任务Task.WaitAny

// Дождаться завершения любой задачи
int numTask = Task.WaitAny(_tasks.ToArray());

所有尝试都以任务在完成之前获得完成状态而结束。

c#
  • 2 个回答
  • 70 Views
Martin Hope
Xzizz
Asked: 2023-05-30 16:52:06 +0000 UTC

无法从 MAUI 社区工具包附加 MediaElement 控件

  • 6

无法连接类型工具包:MediaElement - 我错过了什么?

https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/mediaelement

项目结构

在此处输入图像描述

主页.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MauiAppDelTest.MainPage">

    <toolkit:MediaElement x:Name="mediaElement"/>

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="Hello, World!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to .NET Multi-platform App UI"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Maui程序.cs

using CommunityToolkit.Maui;
using Microsoft.Extensions.Logging;

namespace MauiAppDelTest;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}

错误很明显

在此处输入图像描述

试图重建: 在此处输入图像描述

    Повторная сборка начата…
1>------ Перестроение всех файлов начато: проект: MauiAppDelTest, Конфигурация: Debug Any CPU ------
Восстановлен F:\Projects\MauiAppDelTest\MauiAppDelTest\MauiAppDelTest.csproj (за 307 мс).
1>F:\Projects\MauiAppDelTest\MauiAppDelTest\Microsoft.Maui.Controls.SourceGen\Microsoft.Maui.Controls.SourceGen.CodeBehindGenerator\MainPage.xaml.sg.cs(25,74,25,86): error CS0103: Имя "mediaElement" не существует в текущем контексте.
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
1>F:\Projects\MauiAppDelTest\MauiAppDelTest\Microsoft.Maui.Controls.SourceGen\Microsoft.Maui.Controls.SourceGen.CodeBehindGenerator\MainPage.xaml.sg.cs(25,74,25,86): error CS0103: Имя "mediaElement" не существует в текущем контексте.
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
1>F:\Projects\MauiAppDelTest\MauiAppDelTest\Microsoft.Maui.Controls.SourceGen\Microsoft.Maui.Controls.SourceGen.CodeBehindGenerator\MainPage.xaml.sg.cs(25,74,25,86): error CS0103: Имя "mediaElement" не существует в текущем контексте.
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
1>F:\Projects\MauiAppDelTest\MauiAppDelTest\Microsoft.Maui.Controls.SourceGen\Microsoft.Maui.Controls.SourceGen.CodeBehindGenerator\MainPage.xaml.sg.cs(25,74,25,86): error CS0103: Имя "mediaElement" не существует в текущем контексте.
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
========== Перестроить все: успешно — 0, неудачно — 1, пропущено — 0 ==========
========== Перестроить запущено в 12:02 PM, заняло 05,930 с ==========

删除 x:Name 并重建:

Повторная сборка начата…
1>------ Перестроение всех файлов начато: проект: MauiAppDelTest, Конфигурация: Debug Any CPU ------
Восстановлен F:\Projects\MauiAppDelTest\MauiAppDelTest\MauiAppDelTest.csproj (за 350 мс).
1>MainPage.xaml(7,6): XamlC error XFC0000: Cannot resolve type "http://schemas.microsoft.com/dotnet/2022/maui/toolkit:toolkit:MediaElement".
1>MainPage.xaml(7,6): XamlC error XFC0000: Cannot resolve type "http://schemas.microsoft.com/dotnet/2022/maui/toolkit:toolkit:MediaElement".
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
1>MainPage.xaml(7,6): XamlC error XFC0000: Cannot resolve type "http://schemas.microsoft.com/dotnet/2022/maui/toolkit:toolkit:MediaElement".
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
1>MainPage.xaml(7,6): XamlC error XFC0000: Cannot resolve type "http://schemas.microsoft.com/dotnet/2022/maui/toolkit:toolkit:MediaElement".
1>Сборка проекта "MauiAppDelTest.csproj" завершена с ошибкой.
========== Перестроить все: успешно — 0, неудачно — 1, пропущено — 0 ==========
========== Перестроить запущено в 12:18 PM, заняло 06,888 с ==========

.cproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
    <TargetFrameworks>net7.0-android;net7.0-ios;net7.0-maccatalyst</TargetFrameworks>
    <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks>
    <!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
    <!-- <TargetFrameworks>$(TargetFrameworks);net7.0-tizen</TargetFrameworks> -->
    <OutputType>Exe</OutputType>
    <RootNamespace>MauiAppDelTest</RootNamespace>
    <UseMaui>true</UseMaui>
    <SingleProject>true</SingleProject>
    <ImplicitUsings>enable</ImplicitUsings>

    <!-- Display name -->
    <ApplicationTitle>MauiAppDelTest</ApplicationTitle>

    <!-- App Identifier -->
    <ApplicationId>com.companyname.mauiappdeltest</ApplicationId>
    <ApplicationIdGuid>78dc532d-cb6b-481e-99f8-1e8ead315bfe</ApplicationIdGuid>

    <!-- Versions -->
    <ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
    <ApplicationVersion>1</ApplicationVersion>

    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">13.1</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
    <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
</PropertyGroup>

<ItemGroup>
    <!-- App Icon -->
    <MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />

    <!-- Splash Screen -->
    <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />

    <!-- Images -->
    <MauiImage Include="Resources\Images\*" />
    <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />

    <!-- Custom Fonts -->
    <MauiFont Include="Resources\Fonts\*" />

    <!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
    <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
    <PackageReference Include="CommunityToolkit.Maui" Version="5.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
</ItemGroup>
c#
  • 1 个回答
  • 48 Views
Martin Hope
Vipz
Asked: 2023-05-08 16:49:57 +0000 UTC

强制属性初始化

  • 5

有一个抽象类和它的派生类。

我需要一个抽象类的一些属性必须идвидивидуальными在派生类中用值初始化,这样在创建这些派生类的时候,我才不会忘记在派生类的构造函数中给这样的属性赋值。

我对抽象类的默认值不满意。

这里在派生类的例子中,C不小心忘Prop2了赋值。

我怎么能注意到我忘记了?

    internal abstract class A 
    {
        public string Prop1 { get; protected set; }
        public string Prop2 { get; protected set; }

        public A(string prop) 
        {
            Prop1 = prop;
        }

    }

    internal abstract class B : A
    {
        protected B(string prop) : base(prop)
        {
            Prop2 = "Значение индивидуальное для производного B класса";
        }
    }

    internal abstract class C : A
    {
        protected C(string prop) : base(prop)
        {
            // Забыл добавить в Prop2 значение индивидуальное для производного С класса
        }
    }
c#
  • 2 个回答
  • 51 Views
Martin Hope
Vipz
Asked: 2023-04-18 21:05:51 +0000 UTC

带浮点数的随机值

  • 5

我需要了解float它与 int in 的关系random.Next()

x和width, 是float

我想在没有截断值的情况下收到所有相同的信息。

float coordX = random.Next((int)x,(int)(x + width));

如果我理解正确,那么 random 类的其他方法和真实方法只能在 0.0 到 1.0 之间工作。

c#
  • 1 个回答
  • 29 Views
Martin Hope
Vipz
Asked: 2023-04-18 15:21:52 +0000 UTC

为什么从 TextBox 复制到 .txt 时会出现额外的换行符?

  • 5

TextBox例如,为什么从句柄复制时会出现额外的换行符.txt?

textBox1.AppendText(text + Environment.NewLine);

当粘贴到 TextBox 本身时,没有多余的行,每个文本都在一个新行上。

但是复制到别处时,行与行之间出现空行。

所以在文本框中:

在此处输入图像描述

如果在 .txt 中处理выделить всё-> копировать->вставить那么

在此处输入图像描述

更新:

不知何故侧身,如果你得到它textBox1.Text,事实证明,线之间是\r\r\n

更新2:

我的错误,变量text已经在末尾\r,我添加Environment.NewLine

c#
  • 1 个回答
  • 32 Views
Martin Hope
Vipz
Asked: 2023-03-18 05:00:19 +0000 UTC

省略卷曲的机会

  • 5

书中代码:

if (password.Length < 8)
 WriteLine("Your password is too short. Use at least 8 characters.");
else
 WriteLine("Your password is strong.");

书中引述:

“仅仅因为你可以省略花括号,你就不应该那样做。没有它们,你的代码不会变得“更有效率”,相反它更难维护并且可能更容易受到攻击。”

问题:

作者为什么这么认为?

他从来没有解释过(,虽然我到处都看到使用不带花括号的用法。

只是出于习惯xD?

c#
  • 1 个回答
  • 34 Views
Martin Hope
Vipz
Asked: 2022-09-20 01:44:35 +0000 UTC

获取类和方法名

  • 0

如何找出类和方法的名称?

也许像这样的事情处理方式不同......

我想catch在块中写这样的东西:

Debag.Writeline($"{Название класса} {Название метода} {ex.Message}")
c#
  • 0 个回答
  • 0 Views
Martin Hope
Vipz
Asked: 2022-09-18 16:50:30 +0000 UTC

从方法返回元组

  • 1

使用这样的元组是否合适(从方法返回GetProduct())或者我应该为此创建一个单独的类?

public static class WarehouseGoods
{
    private static object productsLock = new object();

    private static List<Product> products = new List<Product>();

    public static void AddProduct(Product product)
    {
        lock (productsLock)
        {
            products.Add(product);
        }
    }

    public static (bool success,Product product) GetProduct()
    {
        Product? product = null;

        lock (productsLock)
        {
            if (products.Count is not 0)
            {
                product = products.ElementAt(0);
                products.RemoveAt(0);

                return (true,product);
            }
            else
            {
                return (false, product);
            }
        }
    }
}

接下来,我只是检查一下bool,以防万一我True使用Product

            var result = WarehouseGoods.GetProduct();

            if (result.success)
            {
                CheckProduct(result.product);
            }

或者你可以检查productxDnull

那怎么正确?

c#
  • 0 个回答
  • 0 Views
Martin Hope
Vipz
Asked: 2022-08-28 23:39:26 +0000 UTC

破译属性

  • -1

mb-md-0 me-md-auto这些Bootstrap 5.2属性是如何解码的?

      <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-dark text-decoration-none">
        <span class="fs-4">Simple header</span>
      </a>
bootstrap
  • 1 个回答
  • 14 Views
Martin Hope
Vipz
Asked: 2022-08-21 18:14:05 +0000 UTC

NullReferenceException 未处理异常

  • 0

我正在尝试解析Json,但有时找不到所需的密钥并且出现异常NullReferenceException

并且处理异常的尝试被NullReferenceException忽略了,无论如何,在这种情况下,在第 3 行抛出异常NullReferenceException

为什么会这样?

            try
            {
                JToken city = sub_obj.Value["info"]["city"]["name"];

                if (city != null)
                {
                    people.sity= ($"{city.ToString()}");
                }
            }
            catch (NullReferenceException)
            {

            }
c#
  • 1 个回答
  • 54 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5