我想使用模式匹配来替换多个if
语句,如下所示的方法Select<T>()
。我想使用switch()
上的声明typeof(T)
。
static class Program
{
static void Main(string[] args)
{
var doc = new Document();
IWire select = doc.Select<IWire>();
}
public static T Select<T>(this Document document) where T : class, IGeneric
{
var t = typeof(T);
if (t.IsAssignableTo(typeof(IWire)))
{
return document.SelectEntity(EntityType.Wire) as T;
}
if (t.IsAssignableTo(typeof(ISolid)))
{
return document.SelectEntity(EntityType.Solid) as T;
}
if (t.IsAssignableTo(typeof(ISurface)))
{
return document.SelectEntity(EntityType.Surface) as T;
}
// imagine a lot of if statements here
return null;
}
} …
Run Code Online (Sandbox Code Playgroud) 我正要使用下面的 C# 代码。
await using (var producerClient = new EventHubProducerClient(ConnectionString, EventHubName))
{
using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
await producerClient.SendAsync(eventBatch);
}
Run Code Online (Sandbox Code Playgroud)
但是在构建服务器中这会失败,因为上面是 C# 8.0 代码并且构建服务器只支持 C# 7.0 代码。有人可以帮我将上面的代码从 C# 8.0 转换为 C# 7.0,因为我无法让它工作吗?
我有一个Task
FooTask
应该在后台调用的。中的一个新功能C# 7.0
是discard
函数。正如已经问过的(C# 7.0 独立丢弃混淆),可以通过Task
两种方式调用。但是,我还没有能够确切地找出这两个调用有何不同以及它们是否有任何区别。
_ = Task.Run(FooTask);
Run Code Online (Sandbox Code Playgroud)
_ = FooTask();
Run Code Online (Sandbox Code Playgroud) 我尝试了一个简单的测试,但它不喜欢变量
作为一个简单的测试,我写了这个(也许它有一些简单的错误,但我也有模式和元组的麻烦)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
Runner runner = new ConsoleApplication2.Runner();
Point p = new ConsoleApplication2.Point();
runner.PrintCoordinates(p);
}
}
public class Point
{
int x = 20;
int y = 50;
public void GetCoordinates(out int a, out int b)
{
a = x;
b = y;
}
}
public class Runner
{
public void PrintCoordinates(Point p)
{
p.GetCoordinates(out int x, out int …
Run Code Online (Sandbox Code Playgroud) C#7有一个新功能,允许我们轻松定义元组,因此我们可以轻松使用包含多个值的结构.
有没有办法将元组用作泛型类型约束或类似?例如,我试图定义以下方法:
public void Write<T>(T value)
where T : (int x, int y)
{
}
Run Code Online (Sandbox Code Playgroud)
我意识到这个特定的例子是毫无意义的,但是我想象其他场景中有一个包含从另一个类型派生的类型的元组会很有用:
static void Main(string[] args)
{
var first = new Derived();
var second = new Derived();
var types = (t: first, u: second);
Write(types);
Console.ReadLine();
}
public static void Write((Base t, Base u) things)
{
Console.WriteLine($"t: {things.t}, u: {things.u}");
}
public class Base { }
public class Derived { }
Run Code Online (Sandbox Code Playgroud)
此示例不起作用,因为first
它second
是类型Derived
.如果我制作它们的类型,Base
这工作正常.
我从Internet获得了一个包含以下代码行的代码
protected override Freezable CreateInstanceCore() => new ExponentialDoubleAnimation();
Run Code Online (Sandbox Code Playgroud)
我没有在visual studio中安装这个版本的C#.所以这显示错误"失踪;".任何人都可以告诉我这行代码中c#5及以下的类似代码是什么?