看作C#无法打开一个Type(我收集的并不是作为特殊情况添加的,因为is-a关系意味着可能有多个不同的情况可能适用),是否有更好的方法来模拟切换类型?
void Foo(object o)
{
if (o is A)
{
((A)o).Hop();
}
else if (o is B)
{
((B)o).Skip();
}
else
{
throw new ArgumentException("Unexpected type: " + o.GetType());
}
}
Run Code Online (Sandbox Code Playgroud) 我有以下查询:
drivers.Select(d => { d.id = 0; d.updated = DateTime.Now; return d; }).ToList();
Run Code Online (Sandbox Code Playgroud)
drivers是一个List,它带有不同的id和更新的值,因此我在更改Select中的值,但这是正确的方法.我已经知道我没有给司机重新分配司机,因为Resharper抱怨它,所以我想如果是这样会更好:
drivers = drivers.Select(d => { d.id = 0; d.updated = DateTime.Now; return d; }).ToList();
Run Code Online (Sandbox Code Playgroud)
但这仍然是某人应该为驱动程序列表中的每个元素分配新值的方式吗?
我正在尝试为专有的 Android 库生成 Xamarin 绑定(换句话说,不幸的是我无法在此处共享此库)。但是我遇到了多态性问题。情况是这样的。
该库公开了 3 个接口Location,MobilityProfile并且Trip都扩展了该接口Reading。
该库还有一个接口Measurement,其中包含Reading getReading();应始终返回上述 3 个接口(Location、MobilityProfile或Trip)之一的方法。
我生成了绑定并编译了运行良好的绑定项目。下一步是在我的 Xamarin 项目中使用 Xamarin.Android 绑定,如下所示:
public void ProcessReading(IReading reading)
{
if (reading == null)
return null;
switch (reading)
{
case ILocation location:
// Process location
break;
case IMobilityProfile mobilityProfile:
// Process mobility profile
break;
case ITrip trip:
// Process trip
break;
default:
throw new NotSupportedException($"Processing the type '{reading.GetType().FullName}' is not …Run Code Online (Sandbox Code Playgroud) 嗨,
我正试图找到如何改进此代码的方法.我想从CreateAttributes方法中删除"if"语句.如果此属性满足某些条件,则此方法的主要思想是将属性添加到列表
internal class FildMap
{
public string ExactTargetFild { get; set; }
public string DbFild { get; set; }
public Type Type { get; set; }
}
internal static class FildMapProcessor
{
private static readonly List<FildMap> Map = new List<FildMap>();
static FildMapProcessor()
{
if(Map.Count == 0)
{
Map.Add(new FildMap {ExactTargetFild = "Address 1", DbFild = "Address1", Type = typeof (string)});
Map.Add(new FildMap { ExactTargetFild = "Date of birth", DbFild = "DateOfBirth", Type = typeof(DateTime) });
Map.Add(new FildMap { ExactTargetFild …Run Code Online (Sandbox Code Playgroud) 如果我希望使用 if (...) else if (...) 语法将我的代码重写为以下代码的带有 switch (...) case 的语法,如何实现?
void Foo(object aObj) {
if (aObj is Dictionary<int,object> ) {
} else if (aObj is string) {
} else if (aObj is int) {
} else if (aObj is MyCustomClass) {
} else {
throw new Exception("unsupported class type.");
}
}
Run Code Online (Sandbox Code Playgroud)