C# 伊勒无法做出决定。如果它知道选择一种方式(“对象”)或另一种方式(“A”)不会产生任何副作用,为什么它不能选择最具体的可能类型呢? using System.Collections.Generic; using System.Linq; using Sys

C# 伊勒无法做出决定。如果它知道选择一种方式(“对象”)或另一种方式(“A”)不会产生任何副作用,为什么它不能选择最具体的可能类型呢? using System.Collections.Generic; using System.Linq; using Sys,c#,linq,generics,inheritance,C#,Linq,Generics,Inheritance,伊勒无法做出决定。如果它知道选择一种方式(“对象”)或另一种方式(“A”)不会产生任何副作用,为什么它不能选择最具体的可能类型呢? using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Sample { public abstract class A { private A(int index) { /* ... *

伊勒无法做出决定。如果它知道选择一种方式(“对象”)或另一种方式(“A”)不会产生任何副作用,为什么它不能选择最具体的可能类型呢?
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Sample
{
    public abstract class A
    {
        private A(int index) { /* ... */ }

        public sealed class A1 : A
        {
            public A1(string text, int index)
                : base(index)
            { /* ... */ }
        }

        public sealed class A2 : A
        {
            public A2(int index)
                : base(index)
            { /* ... */ }
        }

        private static Regex _regex = new Regex(@"(to be)|(not to be)");
        public static IEnumerable<A> Frob(string frobbable)
        {
            return _regex.Matches(frobbable)
                .Cast<Match>()
                .Select((match, i) =>
                {
                    if (match.Groups[1].Success)
                    {
                        return new A1(match.Groups[1].Value, i);
                    }
                    else
                    {
                        return new A2(i);
                    }
                });
        }
    }
}
if (match.Groups[1].Success)
    return (A)(new A1(match.Groups[1].Value, i));
else
    return (A)(new A2(i));
A returnValue;

if (match.Groups[1].Success)
    returnValue = new A1(match.Groups[1].Value, i);
else
    returnValue = new A2(i);

return returnValue;
.Cast<Match>()
.Select<Match, A>((match, i) =>
{
    if (match.Groups[1].Success)
        return new A1(match.Groups[1].Value, i);
    else
        return new A2(i);
});
Tr M<X>(X x1 … X xm)
void M<X>(X x1, X x2) {}

A1 a1 = new A1();
A2 a2 = new A2();
M(a1, a2);