从 Uncle Bob 的书 Clean Code(示例是在 Java 中编写的,所以这是我的第一个 Java 翻译),我一直在玩质数重构示例。
问题是:您将如何重构以下代码?
这里有 4 个版本:UglyVersion :-)、BobVersion、PeteVersion、PeteVersionClassMember。我这样做是为了好玩,希望你也喜欢:-)
class ProgramBad
{
static void Main()
{
int[] result = GeneratePrimes.generatePrimes(30);
foreach (var i in result)
Console.Write(i.ToString() + ", ");
}
}
/// <summary>
/// Given an array of integers starting at 2, cross out the multiples of 2. Fine the next
/// uncrossed integer, and cross out all of its multiples.
/// Repeat until you have passed the square root of the maximum value …Run Code Online (Sandbox Code Playgroud) 如何在MSTest中断言返回的集合的顺序是否正确?
[TestMethod]
public void when_sorting_movies_it_should_be_able_to_sort_all_movies_by_title_descending()
{
populateTestMovies(movie_collection);
MovieLibrary movieLibrary = new MovieLibrary(movie_collection);
IEnumerable<Movie> results = movieLibrary.sort_all_movies_by_title_descending();
Assert.IsTrue(results.Contains(theres_something_about_mary));
Assert.IsTrue(results.Contains(the_ring));
Assert.IsTrue(results.Contains(shrek));
Assert.IsTrue(results.Contains(pirates_of_the_carribean));
Assert.IsTrue(results.Contains(indiana_jones_and_the_temple_of_doom));
Assert.IsTrue(results.Contains(cars));
Assert.IsTrue(results.Contains(a_bugs_life));
Assert.AreEqual(7, results.Count());
}
Run Code Online (Sandbox Code Playgroud) 我想通过转换为int的字符串来命令我的列表:
var orderedListOfRfidTags = uow.RfidTags.OrderBy(t => Convert.ToInt32(t.Number)).ToList();
Run Code Online (Sandbox Code Playgroud)
但得到:不支持'ToInt32'方法.
我试图从WPF中的BackgroundWorker中读取复选框的值:
这不起作用:
bool? isSleepChecked = checkBoxSleep.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{ return checkBoxSleep.IsChecked;});
Run Code Online (Sandbox Code Playgroud)
无法将匿名方法转换为委托类型'System.Threading.ThreadStart',因为块中的某些返回类型不能隐式转换为委托返回类型
编辑 - 这是HB的答案,使用委托而不是lambda表达,我发现它更具可读性
bool? isSleepChecked = (bool?)checkBoxSleep.Dispatcher.Invoke(new Func<bool?>(delegate { return checkBoxSleep.IsChecked; }));
Run Code Online (Sandbox Code Playgroud) 使用 Serilog 的 ASP.NET Core 5 Razor 页面
UseStatusCodePagesWithReExecute 按预期工作,并在进入我的 /CustomError 页面后重新执行页面。
如何抑制对重新执行页面的第二次调用的 Serilog 日志记录?
密码-postgres完整示例
// program.cs
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
// if only do warning, then will get duplicate error messages when an exception is thrown, then again when re-executed
// we do get 2 error message per single error, but only 1 stack trace
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Fatal)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, …Run Code Online (Sandbox Code Playgroud) 问题:如果某个数字超出其类型的范围,您如何使程序失败?
下面的代码给出了200万以下素数之和的错误答案,因为我使用了int而不是long.
[TestMethod]
public void CalculateTheSumOfPrimesBelow2million()
{
int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
Assert.AreEqual(1, result); // 1,179,908,154 .. this was what I got with an int...
// correct answer was 142,913,828,922 with a long
}
public static class PrimeTester
{
public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow)
{
// we know 2 is a prime number
int sumOfPrimes = 2;
int currentNumberBeingTested = 3;
while (currentNumberBeingTested < maxPrimeBelow)
{
double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);
bool isPrime = true;
for (int i = 2; …Run Code Online (Sandbox Code Playgroud) 我正在测试MvcContrib的网格进行排序.
我使用LightSpeed作为我的ORM
问题:编译错误:listOfRfidTags = ...
无法从用法中推断出方法'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable,System.Func,System.Collections.Generic.IComparer)'的类型参数.尝试显式指定类型参数.
public ActionResult Index(GridSortOptions sort)
{
IEnumerable<RfidTag> listOfRfidTags = uow.RfidTags;
if(sort.Column != null) {
listOfRfidTags = listOfRfidTags.OrderBy(sort.Column, sort.Direction);
}
ViewData["sort"] = sort;
return View(listOfRfidTags);
}
Run Code Online (Sandbox Code Playgroud)
视图:
@Html.Grid(Model).Columns(column =>{
column.For(a => Html.ActionLink("Edit", "Edit", new { id = a.Id })).Named("Edit");
column.For(a => a.TagCode).Named("TagCode").Sortable(true);
column.For(a => a.Number);
})
Run Code Online (Sandbox Code Playgroud) 使用MVC3和实体框架.
我试图从数据模型中获得验证
问题:在实体框架保存中,如何自动为我的伙伴类添加[MetadataType标签?
[EdmEntityTypeAttribute(NamespaceName="ModelValidationTestModel", Name="Person")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
[MetadataType(typeof(Person_Validation))] // I want EF to put this line in automatically
public partial class Person : EntityObject
Run Code Online (Sandbox Code Playgroud)
...
[Bind(Exclude="PersonID")]
public class Person_Validation
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用示例来自:http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
我正在调查如何在循环内部修改循环结束值.这是.NET2代码(我正在使用VB).我明白这不太理想,但可以做到吗?
'inital value is 31
Dim currentNumberOfRowsInDataTable As Int32 = dataTable.Rows.Count - 1
For i As Integer = 0 To currentNumberOfRowsInDataTable
Try
If (dataTable.Rows(i)("DataItemSection") = "Platforms") Then
Dim newRow As DataRow = rearrangedDataTable.NewRow()
'do stuff
dataTable.Rows.RemoveAt(i)
'decrement to 30, however this has no influence on the loop
currentNumberOfRowsInDataTable -= 1
End If
Catch
'problem is that loop always goes to 31, whereas I want it to go to 30
'so need to swallow the exception here
End Try
Next
Run Code Online (Sandbox Code Playgroud)
编辑 …
我正在尝试使用 NUnit 2.6.4 将这个工作 .NET2 C# 转换为 .NET2 VB.NET
[Test]
public void Test() {
Assert.Throws<Exception>(delegate {
DoSomething(2);
});
}
public void DoSomething(int i) {
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
然后进入VB:
<Test> _
Public Sub Test()
Assert.Throws(Of Exception)(Sub() DoSomething(2))
End Sub
Public Sub DoSomething(i As Integer)
Throw New Exception()
End Sub
Run Code Online (Sandbox Code Playgroud)
这适用于 .NET4 但不适用于 .NET2 - 因为我使用的是匿名方法...但是如何在 VB.NET 中表达 .NET2 中的委托
就像是:AddressOf DoSomething(2)
感谢审稿人找到重复内容:How do I target attribute for a record class?
.NET 5.0 Web API不适用于具有所需属性的记录也与之相关。
我试图理解为什么 3. 位置记录属性在下面不起作用。
这是一个新的 ASP.NET Core Razor Pages Web 应用程序,其源代码位于https://github.com/djhmateer/record-test
https://daveabrock.com/2020/11/18/simplify-api-models-with-records似乎已经让它与 API 一起使用。
public class LoginModelNRTB : PageModel
{
[BindProperty]
// there will never be an InputModel on get
// but if we set to nullable InputModel then the cshtml will produce dereference warnings
// https://stackoverflow.com/a/54973095/26086
// so this will get rid of the warnings as we are happy we will never …Run Code Online (Sandbox Code Playgroud) 请参阅下面的第二位代码..代码无法编译.我试图找出anon方法,我明白了..
但不是不使用我在网上找到的匿名方法的例子,它不能编译
使用VS2008 ..编译到.NET3.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestAnonymousMethods
{
public class Program
{
// using an anon method
static void Mainx(string[] args)
{
int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers,
// this is the anonymous method below
delegate(int integer)
{
return (integer % 2 == 0);
}
);
foreach (int integer in _integers)
Console.WriteLine(integer);
foreach (int integer in evenIntegers)
Console.WriteLine(integer);
}
// …Run Code Online (Sandbox Code Playgroud) 这工作:
//delegate
Parallel.For(1023456789, 1033456789, delegate(long i)
{
if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
);
//lambda expression
Parallel.For(1023456789, 1033456789, i =>
{
if (i%10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
);
Run Code Online (Sandbox Code Playgroud)
是否可以使用Func重写此逻辑?我在这里试过..不编译.
var list = new List<long>();
Parallel.For(1023456789, 1033456789, Blah(i, ref list));
public static Func<long> Blah(long i, ref List<long> list)
{
if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图看看它是否可以完成.
c# ×10
.net ×2
asp.net-core ×2
delegates ×2
linq ×2
vb.net ×2
lambda ×1
lightspeed ×1
mvccontrib ×1
nunit ×1
razor-pages ×1
record ×1
refactoring ×1
serilog ×1
wpf ×1