25

我正在为我的 IoC 类库重写我的流利界面,当我重构一些代码以便通过基类共享一些通用功能时,我遇到了一个障碍。

注意:这是我想做的事情,而不是我必须做的事情。如果我不得不使用不同的语法,我会的,但如果有人知道如何让我的代码按照我想要的方式编译,那将是最受欢迎的。

我希望某些扩展方法可用于特定的基类,并且这些方法应该是通用的,具有一种通用类型,与方法的参数相关,但这些方法还应该返回与它们的特定后代相关的特定类型'被调用。

使用代码示例比上面的描述更好。

这是一个简单而完整的例子,说明什么不起作用

using System;

namespace ConsoleApplication16
{
    public class ParameterizedRegistrationBase { }
    public class ConcreteTypeRegistration : ParameterizedRegistrationBase
    {
        public void SomethingConcrete() { }
    }
    public class DelegateRegistration : ParameterizedRegistrationBase
    {
        public void SomethingDelegated() { }
    }

    public static class Extensions
    {
        public static ParameterizedRegistrationBase Parameter<T>(
            this ParameterizedRegistrationBase p, string name, T value)
        {
            return p;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ConcreteTypeRegistration ct = new ConcreteTypeRegistration();
            ct
                .Parameter<int>("age", 20)
                .SomethingConcrete(); // <-- this is not available

            DelegateRegistration del = new DelegateRegistration();
            del
                .Parameter<int>("age", 20)
                .SomethingDelegated(); // <-- neither is this
        }
    }
}

如果你编译这个,你会得到:

'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingConcrete' and no extension method 'SomethingConcrete'...
'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingDelegated' and no extension method 'SomethingDelegated'...

我想要的是扩展方法 ( Parameter<T>) 能够在ConcreteTypeRegistration和上调用DelegateRegistration,并且在这两种情况下,返回类型都应该与调用扩展的类型相匹配。

问题如下:

我想写:

ct.Parameter<string>("name", "Lasse")
            ^------^
            notice only one generic argument

但也Parameter<T>返回一个与它被调用的类型相同的对象,这意味着:

ct.Parameter<string>("name", "Lasse").SomethingConcrete();
^                                     ^-------+-------^
|                                             |
+---------------------------------------------+
   .SomethingConcrete comes from the object in "ct"
   which in this case is of type ConcreteTypeRegistration

有什么办法可以欺骗编译器为我实现这一飞跃?

如果我向方法中添加两个泛型类型参数Parameter,类型推断会强制我要么提供两者,要么不提供,这意味着:

public static TReg Parameter<TReg, T>(
    this TReg p, string name, T value)
    where TReg : ParameterizedRegistrationBase

给了我这个:

Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments
Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments

这同样糟糕。

我可以轻松地重组类,甚至通过将它们引入层次结构来使方法成为非扩展方法,但我的问题是我是否可以避免为两个后代复制方法,并且以某种方式只声明一次, 对于基类。

让我重新表述一下。有没有办法更改上面第一个代码示例中的类,以便保留 Main-method 中的语法,而无需复制相关方法?

代码必须与 C# 3.0 和 4.0 兼容。


编辑:我不想将两个泛型类型参数都留给推理的原因是,对于某些服务,我想为一种类型的构造函数参数指定一个参数值,但传入一个后代值。目前,指定参数值和要调用的正确构造函数的匹配是使用参数的名称和类型完成的。

让我举个例子吧:

ServiceContainerBuilder.Register<ISomeService>(r => r
    .From(f => f.ConcreteType<FileService>(ct => ct
        .Parameter<Stream>("source", new FileStream(...)))));
                  ^--+---^               ^---+----^
                     |                       |
                     |                       +- has to be a descendant of Stream
                     |
                     +- has to match constructor of FileService

如果我将两者都留给类型推断,则参数类型将是FileStream,而不是Stream

4

6 回答 6

18

我想创建一个扩展方法,可以枚举事物列表,并返回特定类型的事物列表。它看起来像这样:

listOfFruits.ThatAre<Banana>().Where(banana => banana.Peel != Color.Black) ...

可悲的是,这是不可能的。此扩展方法的建议签名如下所示:

public static IEnumerable<TResult> ThatAre<TSource, TResult>
    (this IEnumerable<TSource> source) where TResult : TSource

...并且对 ThatAre<> 的调用失败,因为需要指定两个类型参数,即使 TSource 可以从用法中推断出来。

按照其他答案中的建议,我创建了两个函数:一个捕获源,另一个允许调用者表达结果:

public static ThatAreWrapper<TSource> That<TSource>
    (this IEnumerable<TSource> source)
{
    return new ThatAreWrapper<TSource>(source);
}

public class ThatAreWrapper<TSource>
{
    private readonly IEnumerable<TSource> SourceCollection;
    public ThatAreWrapper(IEnumerable<TSource> source)
    {
        SourceCollection = source;
    }
    public IEnumerable<TResult> Are<TResult>() where TResult : TSource
    {
        foreach (var sourceItem in SourceCollection)
            if (sourceItem is TResult) yield return (TResult)sourceItem;
        }
    }
}

这将导致以下调用代码:

listOfFruits.That().Are<Banana>().Where(banana => banana.Peel != Color.Black) ...

......这还不错。

请注意,由于泛型类型约束,以下代码:

listOfFruits.That().Are<Truck>().Where(truck => truck.Horn.IsBroken) ...

将无法在 Are() 步骤编译,因为卡车不是水果。这胜过提供的 .OfType<> 函数:

listOfFruits.OfType<Truck>().Where(truck => truck.Horn.IsBroken) ...

这可以编译,但总是产生零结果,而且尝试确实没有任何意义。让编译器帮助您发现这些东西要好得多。

于 2010-11-05T14:30:37.290 回答
15

如果您只有两种特定类型的注册(您的问题似乎就是这种情况),您可以简单地实现两种扩展方法:

public static DelegateRegistration Parameter<T>( 
   this DelegateRegistration p, string name, T value); 

public static ConcreteTypeRegistration Parameter<T>( 
   this ConcreteTypeRegistration p, string name, T value); 

然后您不需要指定类型参数,因此类型推断将在您提到的示例中起作用。请注意,您可以通过委托给具有两个类型参数(您的问题中的那个)的单个通用扩展方法来实现这两种扩展方法。


通常,C# 不支持o.Foo<int, ?>(..)仅推断第二个类型参数(这将是一个不错的功能 - F# 拥有它并且非常有用:-))。您可能可以实现一个允许您编写此代码的解决方法(基本上,通过将调用分为两个方法调用,以获得可以应用类型推断的两个位置):

FooTrick<int>().Apply(); // where Apply is a generic method

这是一个演示结构的伪代码:

// in the original object
FooImmediateWrapper<T> FooTrick<T>() { 
  return new FooImmediateWrapper<T> { InvokeOn = this; } 
}
// in the FooImmediateWrapper<T> class
(...) Apply<R>(arguments) { 
  this.InvokeOn.Foo<T, R>(arguments);
}
于 2010-05-23T22:37:43.757 回答
2

为什么不指定零类型参数?两者都可以在您的样本中推断出来。如果这对您来说不是一个可接受的解决方案,我也经常遇到这个问题,并且没有简单的方法来解决“仅推断一个类型参数”的问题。所以我会使用重复的方法。

于 2010-05-23T22:21:45.743 回答
1

以下情况如何:

使用您提供的定义: public static TReg Parameter<TReg, T>( this TReg p, string name, T value) where TReg : ParameterizedRegistrationBase

然后强制转换参数,以便推理引擎获得正确的类型:

ServiceContainerBuilder.Register<ISomeService>(r => r
.From(f => f.ConcreteType<FileService>(ct => ct
    .Parameter("source", (Stream)new FileStream(...)))));
于 2010-05-23T22:47:13.313 回答
0

我认为您需要在两个不同的表达式之间拆分两个类型参数;使显式成为扩展方法的参数类型的一部分,因此推断可以将其拾取。

假设您声明了一个包装类:

public class TypedValue<TValue>
{
    public TypedValue(TValue value)
    {
        Value = value;
    }

    public TValue Value { get; private set; }
}

然后您的扩展方法为:

public static class Extensions
{
    public static TReg Parameter<TValue, TReg>(
        this TReg p, string name, TypedValue<TValue> value) 
        where TReg : ParameterizedRegistrationBase
    {
        // can get at value.Value
        return p;
    }
}

加上一个更简单的重载(上面实际上可以称之为这个):

public static class Extensions
{
    public static TReg Parameter<TValue, TReg>(
        this TReg p, string name, TValue value) 
        where TReg : ParameterizedRegistrationBase
    {
        return p;
    }
}

现在,在您乐于推断参数值类型的简单情况下:

ct.Parameter("name", "Lasse")

但是在需要显式声明类型的情况下,可以这样做:

ct.Parameter("list", new TypedValue<IEnumerable<int>>(new List<int>()))

看起来很难看,但希望比简单的完全推断类型更罕见。

请注意,您可以只使用无包装器重载并编写:

ct.Parameter("list", (IEnumerable<int>)(new List<int>()))

但这当然有一个缺点,就是如果你出错了,会在运行时失败。不幸的是,我现在远离我的 C# 编译器,所以如果这太远了,我们深表歉意。

于 2010-05-23T22:50:58.047 回答
0

我会使用解决方案:

public class JsonDictionary
{
    public static readonly Key<int> Foo = new Key<int> { Name = "FOO" };
    public static readonly Key<string> Bar = new Key<string> { Name = "BAR" };
        
    IDictionary<string, object> _data;
    public JsonDictionary()
    {
        _data = new Dictionary<string, object>();
    }
    
    public void Set<T>(Key<T> key, T obj)
    {
        _data[key.Name] = obj;
    }

    public T Get<T>(Key<T> key)
    {
        return (T)_data[key.Name];
    }
    
    public class Key<T>
    {
        public string Name { get; init; }
    }
}

看:

于 2021-09-06T06:59:31.810 回答