371

看到 C# 不能switch在类型上使用(我认为没有将其添加为特例,因为is关系意味着可能应用多个不同case的类型),除此之外还有更好的方法来模拟打开类型吗?

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());
    }
}
4

31 回答 31

365

使用 Visual Studio 2017 (Release 15.*) 附带的 C# 7,您可以在case语句中使用类型(模式匹配):

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

使用 C# 6,您可以使用带有nameof() 运算符的 switch 语句(感谢@Joey Adams):

switch(o.GetType().Name) {
    case nameof(AType):
        break;
    case nameof(BType):
        break;
}

对于 C# 5 及更早版本,您可以使用 switch 语句,但您必须使用包含类型名称的魔术字符串......这不是特别友好的重构(感谢@nukefusion)

switch(o.GetType().Name) {
  case "AType":
    break;
}
于 2008-11-18T15:08:41.907 回答
286

C# 中肯定缺少切换类型(更新:在 C#7 / VS 2017 中支持切换类型 -请参阅 Zachary Yates 的回答)。为了在没有大型 if/else if/else 语句的情况下执行此操作,您需要使用不同的结构。不久前我写了一篇博文,详细介绍了如何构建 TypeSwitch 结构。

https://docs.microsoft.com/archive/blogs/jaredpar/switching-on-types

短版:TypeSwitch 旨在防止冗余转换并提供类似于普通 switch/case 语句的语法。例如,这是 TypeSwitch 在标准 Windows 窗体事件中的作用

TypeSwitch.Do(
    sender,
    TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
    TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
    TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));

TypeSwitch 的代码实际上非常小,可以很容易地放入您的项目中。

static class TypeSwitch {
    public class CaseInfo {
        public bool IsDefault { get; set; }
        public Type Target { get; set; }
        public Action<object> Action { get; set; }
    }

    public static void Do(object source, params CaseInfo[] cases) {
        var type = source.GetType();
        foreach (var entry in cases) {
            if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) {
                entry.Action(source);
                break;
            }
        }
    }

    public static CaseInfo Case<T>(Action action) {
        return new CaseInfo() {
            Action = x => action(),
            Target = typeof(T)
        };
    }

    public static CaseInfo Case<T>(Action<T> action) {
        return new CaseInfo() {
            Action = (x) => action((T)x),
            Target = typeof(T)
        };
    }

    public static CaseInfo Default(Action action) {
        return new CaseInfo() {
            Action = x => action(),
            IsDefault = true
        };
    }
}
于 2008-11-18T15:44:53.563 回答
103

一种选择是有一本 from Typeto Action(或其他一些代表)的字典。根据类型查找动作,然后执行。我以前在工厂里用过这个。

于 2008-11-18T15:07:42.143 回答
49

有了JaredPar 的回答我写了一个他的类的变体,TypeSwitch它使用类型推断来获得更好的语法:

class A { string Name { get; } }
class B : A { string LongName { get; } }
class C : A { string FullName { get; } }
class X { public string ToString(IFormatProvider provider); }
class Y { public string GetIdentifier(); }

public string GetName(object value)
{
    string name = null;
    TypeSwitch.On(value)
        .Case((C x) => name = x.FullName)
        .Case((B x) => name = x.LongName)
        .Case((A x) => name = x.Name)
        .Case((X x) => name = x.ToString(CultureInfo.CurrentCulture))
        .Case((Y x) => name = x.GetIdentifier())
        .Default((x) => name = x.ToString());
    return name;
}

请注意,Case()方法的顺序很重要。


获取我的TypeSwitch课程的完整和注释代码。这是一个工作的缩写版本:

public static class TypeSwitch
{
    public static Switch<TSource> On<TSource>(TSource value)
    {
        return new Switch<TSource>(value);
    }

    public sealed class Switch<TSource>
    {
        private readonly TSource value;
        private bool handled = false;

        internal Switch(TSource value)
        {
            this.value = value;
        }

        public Switch<TSource> Case<TTarget>(Action<TTarget> action)
            where TTarget : TSource
        {
            if (!this.handled && this.value is TTarget)
            {
                action((TTarget) this.value);
                this.handled = true;
            }
            return this;
        }

        public void Default(Action<TSource> action)
        {
            if (!this.handled)
                action(this.value);
        }
    }
}
于 2012-04-05T08:46:31.337 回答
17

您可以在 C# 7 或更高版本中使用模式匹配:

switch (foo.GetType())
{
    case var type when type == typeof(Player):
        break;
    case var type when type == typeof(Address):
        break;
    case var type when type == typeof(Department):
        break;
    case var type when type == typeof(ContactType):
        break;
    default:
        break;
}
于 2019-01-25T21:40:38.333 回答
14

创建一个超类(S)并让 A 和 B 继承它。然后在 S 上声明一个每个子类都需要实现的抽象方法。

这样做,“foo”方法还可以将其签名更改为 Foo(S o),使其类型安全,并且您不需要抛出那个丑陋的异常。

于 2008-11-18T15:07:58.227 回答
9

是的,感谢 C# 7 可以实现。这是它的完成方式(使用表达式模式):

switch (o)
{
    case A a:
        a.Hop();
        break;
    case B b:
        b.Skip();
        break;
    case C _: 
        return new ArgumentException("Type C will be supported in the next version");
    default:
        return new ArgumentException("Unexpected type: " + o.GetType());
}
于 2017-04-05T13:53:57.767 回答
8

如果您使用的是 C# 4,则可以利用新的动态功能来实现一个有趣的替代方案。我并不是说这更好,事实上它似乎很可能会更慢,但它确实有一定的优雅。

class Thing
{

  void Foo(A a)
  {
     a.Hop();
  }

  void Foo(B b)
  {
     b.Skip();
  }

}

以及用法:

object aOrB = Get_AOrB();
Thing t = GetThing();
((dynamic)t).Foo(aorB);

这样做的原因是 C# 4 动态方法调用在运行时而不是编译时解决其重载。我最近写了更多关于这个想法的文章。再一次,我想重申一下,这可能比所有其他建议的表现都差,我只是出于好奇而提供它。

于 2008-11-19T15:22:38.897 回答
7

你真的应该重载你的方法,而不是试图自己消除歧义。到目前为止,大多数答案都没有考虑到未来的子类,这可能会在以后导致非常糟糕的维护问题。

于 2008-11-18T15:16:34.697 回答
7

对于内置类型,您可以使用 TypeCode 枚举。请注意 GetType() 有点慢,但在大多数情况下可能不相关。

switch (Type.GetTypeCode(someObject.GetType()))
{
    case TypeCode.Boolean:
        break;
    case TypeCode.Byte:
        break;
    case TypeCode.Char:
        break;
}

对于自定义类型,您可以创建自己的枚举,以及具有抽象属性或方法的接口或基类...

属性的抽象类实现

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public abstract class Foo
{
    public abstract FooTypes FooType { get; }
}
public class FooFighter : Foo
{
    public override FooTypes FooType { get { return FooTypes.FooFighter; } }
}

方法的抽象类实现

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public abstract class Foo
{
    public abstract FooTypes GetFooType();
}
public class FooFighter : Foo
{
    public override FooTypes GetFooType() { return FooTypes.FooFighter; }
}

属性的接口实现

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public interface IFooType
{
    FooTypes FooType { get; }
}
public class FooFighter : IFooType
{
    public FooTypes FooType { get { return FooTypes.FooFighter; } }
}

方法的接口实现

public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };
public interface IFooType
{
    FooTypes GetFooType();
}
public class FooFighter : IFooType
{
    public FooTypes GetFooType() { return FooTypes.FooFighter; }
}

我的一位同事也刚刚告诉我:这样做的好处是您可以将它用于几乎任何类型的对象,而不仅仅是您定义的对象。它的缺点是体积更大,速度更慢。

首先定义一个像这样的静态类:

public static class TypeEnumerator
{
    public class TypeEnumeratorException : Exception
    {
        public Type unknownType { get; private set; }
        public TypeEnumeratorException(Type unknownType) : base()
        {
            this.unknownType = unknownType;
        }
    }
    public enum TypeEnumeratorTypes { _int, _string, _Foo, _TcpClient, };
    private static Dictionary<Type, TypeEnumeratorTypes> typeDict;
    static TypeEnumerator()
    {
        typeDict = new Dictionary<Type, TypeEnumeratorTypes>();
        typeDict[typeof(int)] = TypeEnumeratorTypes._int;
        typeDict[typeof(string)] = TypeEnumeratorTypes._string;
        typeDict[typeof(Foo)] = TypeEnumeratorTypes._Foo;
        typeDict[typeof(System.Net.Sockets.TcpClient)] = TypeEnumeratorTypes._TcpClient;
    }
    /// <summary>
    /// Throws NullReferenceException and TypeEnumeratorException</summary>
    /// <exception cref="System.NullReferenceException">NullReferenceException</exception>
    /// <exception cref="MyProject.TypeEnumerator.TypeEnumeratorException">TypeEnumeratorException</exception>
    public static TypeEnumeratorTypes EnumerateType(object theObject)
    {
        try
        {
            return typeDict[theObject.GetType()];
        }
        catch (KeyNotFoundException)
        {
            throw new TypeEnumeratorException(theObject.GetType());
        }
    }
}

然后你可以像这样使用它:

switch (TypeEnumerator.EnumerateType(someObject))
{
    case TypeEnumerator.TypeEnumeratorTypes._int:
        break;
    case TypeEnumerator.TypeEnumeratorTypes._string:
        break;
}
于 2013-11-15T19:45:16.707 回答
7

C# 8 对模式匹配的增强使得这样做成为可能。在某些情况下,它可以完成工作并且更简洁。

        public Animal Animal { get; set; }
        ...
        var animalName = Animal switch
        {
            Cat cat => "Tom",
            Mouse mouse => "Jerry",
            _ => "unknown"
        };
于 2020-01-14T08:50:19.773 回答
6

我喜欢 Virtlink使用隐式类型来使开关更具可读性,但我不喜欢提前退出是不可能的,而且我们正在做分配。让我们把性能调高一点。

public static class TypeSwitch
{
    public static void On<TV, T1>(TV value, Action<T1> action1)
        where T1 : TV
    {
        if (value is T1) action1((T1)value);
    }

    public static void On<TV, T1, T2>(TV value, Action<T1> action1, Action<T2> action2)
        where T1 : TV where T2 : TV
    {
        if (value is T1) action1((T1)value);
        else if (value is T2) action2((T2)value);
    }

    public static void On<TV, T1, T2, T3>(TV value, Action<T1> action1, Action<T2> action2, Action<T3> action3)
        where T1 : TV where T2 : TV where T3 : TV
    {
        if (value is T1) action1((T1)value);
        else if (value is T2) action2((T2)value);
        else if (value is T3) action3((T3)value);
    }

    // ... etc.
}

嗯,这让我的手指受伤。让我们在 T4 中进行:

<#@ template debug="false" hostSpecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ import namespace="System.Linq" #> 
<#@ import namespace="System.IO" #> 
<#
    string GenWarning = "// THIS FILE IS GENERATED FROM " + Path.GetFileName(Host.TemplateFile) + " - ANY HAND EDITS WILL BE LOST!";
    const int MaxCases = 15;
#>
<#=GenWarning#>

using System;

public static class TypeSwitch
{
<# for(int icase = 1; icase <= MaxCases; ++icase) {
    var types = string.Join(", ", Enumerable.Range(1, icase).Select(i => "T" + i));
    var actions = string.Join(", ", Enumerable.Range(1, icase).Select(i => string.Format("Action<T{0}> action{0}", i)));
    var wheres = string.Join(" ", Enumerable.Range(1, icase).Select(i => string.Format("where T{0} : TV", i)));
#>
    <#=GenWarning#>

    public static void On<TV, <#=types#>>(TV value, <#=actions#>)
        <#=wheres#>
    {
        if (value is T1) action1((T1)value);
<# for(int i = 2; i <= icase; ++i) { #>
        else if (value is T<#=i#>) action<#=i#>((T<#=i#>)value);
<#}#>
    }

<#}#>
    <#=GenWarning#>
}

稍微调整一下 Virtlink 的例子:

TypeSwitch.On(operand,
    (C x) => name = x.FullName,
    (B x) => name = x.LongName,
    (A x) => name = x.Name,
    (X x) => name = x.ToString(CultureInfo.CurrentCulture),
    (Y x) => name = x.GetIdentifier(),
    (object x) => name = x.ToString());

可读且快速。现在,正如每个人都在他们的答案中不断指出的那样,并且考虑到这个问题的性质,顺序在类型匹配中很重要。所以:

  • 首先放置叶子类型,然后放置基本类型。
  • 对于对等类型,将更可能的匹配放在首位以最大化性能。
  • 这意味着不需要特殊的默认情况。相反,只需使用 lambda 中最基础的类型,并将其放在最后。
于 2013-06-18T15:59:46.770 回答
5

鉴于继承有助于将对象识别为多个类型,我认为切换可能会导致歧义。例如:

情况1

{
  string s = "a";
  if (s is string) Print("Foo");
  else if (s is object) Print("Bar");
}

案例2

{
  string s = "a";
  if (s is object) Print("Foo");
  else if (s is string) Print("Bar");
}

因为 s 是一个字符串一个对象。我认为,当您编写 a 时,switch(foo)您希望 foo 匹配一个且仅一个case语句。使用 switch 类型,你编写 case 语句的顺序可能会改变整个 switch 语句的结果。我认为那是错误的。

您可以考虑对“typeswitch”语句的类型进行编译器检查,检查枚举类型是否相互继承。但这并不存在。

foo is T不一样foo.GetType() == typeof(T)!!

于 2011-05-06T11:56:37.893 回答
4

我要么

  • 使用方法重载(就像x0n一样),或者
  • 使用子类(就像Pablo一样),或者
  • 应用访问者模式
于 2008-11-18T15:12:30.197 回答
4

另一种方法是定义一个接口 IThing ,然后在两个类中实现它,这是代码片段:

public interface IThing
{
    void Move();
}

public class ThingA : IThing
{
    public void Move()
    {
        Hop();
    }

    public void Hop(){  
        //Implementation of Hop 
    }

}

public class ThingA : IThing
{
    public void Move()
    {
        Skip();
    }

    public void Skip(){ 
        //Implementation of Skip    
    }

}

public class Foo
{
    static void Main(String[] args)
    {

    }

    private void Foo(IThing a)
    {
        a.Move();
    }
}
于 2008-11-18T15:57:21.370 回答
4

根据 C# 7.0 规范,您可以在 acase的 a中声明一个局部变量switch

object a = "Hello world";
switch (a)
{
    case string myString:
        // The variable 'a' is a string!
        break;
    case int myInt:
        // The variable 'a' is an int!
        break;
    case Foo myFoo:
        // The variable 'a' is of type Foo!
        break;
}

这是做这种事情的最好方法,因为它只涉及强制转换和压栈操作,这是解释器在按位操作和boolean条件之后可以运行的最快操作。

将其与 a 进行比较Dictionary<K, V>,内存使用量要少得多:保存字典需要更多的 RAM 空间,并且 CPU 需要更多的计算来创建两个数组(一个用于键,另一个用于值)并收集要放置的键的哈希码值到各自的键。

if因此,据我所知,除非您只想对运算符使用--块,否则我认为不会存在更快的方法then,如下所示:elseis

object a = "Hello world";
if (a is string)
{
    // The variable 'a' is a string!
} else if (a is int)
{
    // The variable 'a' is an int!
} // etc.
于 2018-09-12T14:51:56.607 回答
3

您可以创建重载方法:

void Foo(A a) 
{ 
    a.Hop(); 
}

void Foo(B b) 
{ 
    b.Skip(); 
}

void Foo(object o) 
{ 
    throw new ArgumentException("Unexpected type: " + o.GetType()); 
}

并将参数转换为dynamictype 以绕过静态类型检查:

Foo((dynamic)something);
于 2013-01-04T12:30:56.557 回答
3

应该与

case type _:

像:

int i = 1;
bool b = true;
double d = 1.1;
object o = i; // whatever you want

switch (o)
{
    case int _:
        Answer.Content = "You got the int";
        break;
    case double _:
        Answer.Content = "You got the double";
        break;
    case bool _:
        Answer.Content = "You got the bool";
        break;
}
于 2019-04-04T12:56:32.937 回答
2

在这种情况下,我通常会得到一个谓词和动作列表。这些方面的东西:

class Mine {
    static List<Func<object, bool>> predicates;
    static List<Action<object>> actions;

    static Mine() {
        AddAction<A>(o => o.Hop());
        AddAction<B>(o => o.Skip());
    }

    static void AddAction<T>(Action<T> action) {
        predicates.Add(o => o is T);
        actions.Add(o => action((T)o);
    }

    static void RunAction(object o) {
        for (int i=0; o < predicates.Count; i++) {
            if (predicates[i](o)) {
                actions[i](o);
                break;
            }
        }
    }

    void Foo(object o) {
        RunAction(o);
    }
}
于 2008-11-18T15:14:04.203 回答
2

创建一个接口IFooable,然后让你AB类实现一个通用方法,然后调用你想要的对应方法:

interface IFooable
{
    public void Foo();
}

class A : IFooable
{
    //other methods ...

    public void Foo()
    {
        this.Hop();
    }
}

class B : IFooable
{
    //other methods ...

    public void Foo()
    {
        this.Skip();
    }
}

class ProcessingClass
{
    public void Foo(object o)
    {
        if (o == null)
            throw new NullRefferenceException("Null reference", "o");

        IFooable f = o as IFooable;
        if (f != null)
        {
            f.Foo();
        }
        else
        {
            throw new ArgumentException("Unexpected type: " + o.GetType());
        }
    }
}

请注意,最好as先检查,is然后再进行转换,因为这样可以进行 2 次转换,因此成本更高。

于 2008-11-18T15:26:02.543 回答
2

您正在寻找Discriminated Unions哪些是 F# 的语言功能,但是您可以通过使用我制作的名为 OneOf 的库来实现类似的效果

https://github.com/mcintyre321/OneOf

switch(and ifand )的主要优点exceptions as control flow是它是编译时安全的 - 没有默认处理程序或失败

void Foo(OneOf<A, B> o)
{
    o.Switch(
        a => a.Hop(),
        b => b.Skip()
    );
}

如果将第三项添加到 o,则会出现编译器错误,因为您必须在 switch 调用中添加处理程序 Func。

您还可以执行 a .Matchwhich 返回一个值,而不是执行一条语句:

double Area(OneOf<Square, Circle> o)
{
    return o.Match(
        square => square.Length * square.Length,
        circle => Math.PI * circle.Radius * circle.Radius
    );
}
于 2017-08-02T08:52:05.103 回答
2

如果您知道您期望的课程,但您仍然没有对象,您甚至可以这样做:

private string GetAcceptButtonText<T>() where T : BaseClass, new()
{
    switch (new T())
    {
        case BaseClassReview _: return "Review";
        case BaseClassValidate _: return "Validate";
        case BaseClassAcknowledge _: return "Acknowledge";
        default: return "Accept";
    }
}
于 2019-04-08T12:42:35.213 回答
2

从 C# 8 开始,您可以使用新开关使其更加简洁。并且使用 discard 选项 _ 您可以避免在不需要时创建不必要的变量,如下所示:

        return document switch {
            Invoice _ => "Is Invoice",
            ShippingList _ => "Is Shipping List",
            _ => "Unknown"
        };

Invoice 和 ShippingList 是类,而 document 是可以是其中任何一个的对象。

于 2020-02-25T02:08:10.330 回答
1

在比较了此处提供的 F# 功能的选项后,我发现 F# 对基于类型的切换有更好的支持(尽管我仍然坚持使用 C#)。
你可能想看看这里这里

于 2008-11-18T15:22:43.907 回答
1

我将创建一个对您的开关有意义的名称和方法名称的接口,让我们分别调用它们:IDoable告诉实现void Do().

public interface IDoable
{
    void Do();
}

public class A : IDoable
{
    public void Hop() 
    {
        // ...
    }

    public void Do()
    {
        Hop();
    }
}

public class B : IDoable
{
    public void Skip() 
    {
        // ...
    }

    public void Do()
    {
        Skip();
    }
}

并将方法更改如下:

void Foo<T>(T obj)
    where T : IDoable
{
    // ...
    obj.Do();
    // ...
}

至少在编译时你是安全的,我怀疑在性能方面它比在运行时检查类型更好。

于 2018-11-08T17:19:55.410 回答
0

我同意 Jon 关于对类名进行操作的哈希。如果您保留您的模式,您可能需要考虑使用“as”构造来代替:

A a = o as A;
if (a != null) {
    a.Hop();
    return;
}
B b = o as B;
if (b != null) {
    b.Skip();
    return;
}
throw new ArgumentException("...");

不同之处在于,当您使用模式时 if (foo is Bar) { ((Bar)foo).Action(); 你正在做两次类型转换。现在也许编译器会优化并且只做一次 - 但我不会指望它。

于 2008-11-18T15:23:21.470 回答
0

正如 Pablo 所建议的,接口方法几乎总是处理这个问题的正确方法。要真正利用 switch,另一种选择是在你的类中使用一个自定义枚举来表示你的类型。

enum ObjectType { A, B, Default }

interface IIdentifiable
{
    ObjectType Type { get; };
}
class A : IIdentifiable
{
    public ObjectType Type { get { return ObjectType.A; } }
}

class B : IIdentifiable
{
    public ObjectType Type { get { return ObjectType.B; } }
}

void Foo(IIdentifiable o)
{
    switch (o.Type)
    {
        case ObjectType.A:
        case ObjectType.B:
        //......
    }
}

这也是在 BCL 中实现的。一个例子是MemberInfo.MemberTypes,另一个是GetTypeCode原始类型,比如:

void Foo(object o)
{
    switch (Type.GetTypeCode(o.GetType())) // for IConvertible, just o.GetTypeCode()
    {
        case TypeCode.Int16:
        case TypeCode.Int32:
        //etc ......
    }
}
于 2013-01-03T03:44:53.763 回答
0

这是一个替代答案,混合了 JaredPar 和 VirtLink 答案的贡献,具有以下约束:

  • switch 构造的行为类似于 function,并接收函数作为case 的参数。
  • 确保它被正确构建,并且始终存在一个默认函数
  • 在第一次匹配后返回(JaredPar 答案为真,VirtLink 答案不为真)。

用法:

 var result = 
   TSwitch<string>
     .On(val)
     .Case((string x) => "is a string")
     .Case((long x) => "is a long")
     .Default(_ => "what is it?");

代码:

public class TSwitch<TResult>
{
    class CaseInfo<T>
    {
        public Type Target { get; set; }
        public Func<object, T> Func { get; set; }
    }

    private object _source;
    private List<CaseInfo<TResult>> _cases;

    public static TSwitch<TResult> On(object source)
    {
        return new TSwitch<TResult> { 
            _source = source,
            _cases = new List<CaseInfo<TResult>>()
        };
    }

    public TResult Default(Func<object, TResult> defaultFunc)
    {
        var srcType = _source.GetType();
       foreach (var entry in _cases)
            if (entry.Target.IsAssignableFrom(srcType))
                return entry.Func(_source);

        return defaultFunc(_source);
    }

    public TSwitch<TResult> Case<TSource>(Func<TSource, TResult> func)
    {
        _cases.Add(new CaseInfo<TResult>
        {
            Func = x => func((TSource)x),
            Target = typeof(TSource)
        });
        return this;
    }
}
于 2016-08-23T10:59:41.593 回答
0

是的 - 只需使用从 C#7 向上命名的稍微奇怪的“模式匹配”来匹配类或结构:

IObject concrete1 = new ObjectImplementation1();
IObject concrete2 = new ObjectImplementation2();

switch (concrete1)
{
    case ObjectImplementation1 c1: return "type 1";         
    case ObjectImplementation2 c2: return "type 2";         
}
于 2018-10-29T12:05:17.510 回答
0

我用

    public T Store<T>()
    {
        Type t = typeof(T);

        if (t == typeof(CategoryDataStore))
            return (T)DependencyService.Get<IDataStore<ItemCategory>>();
        else
            return default(T);
    }
于 2018-11-28T23:04:51.680 回答
0

试着走这条路:

public void Test(BaseType @base)
{
    switch (@base)
    {
        case ConcreteType concrete:
            DoSomething(concrete);
            break;

        case AnotherConcrete concrete:
            DoSomething(concrete);
            break;
    }
}
于 2020-07-14T11:25:27.173 回答