简体   繁体   English

C#试图简化通用类型接口的通用扩展功能

[英]C# trying to simplify Generic Extension Function for Generic Typed Interface

Here is the code, last line is the highlight of what I am doing: 这是代码,最后一行是我正在做的事情的重点:

public interface IHasContext<TContext> {
  TContext Context {get; set;}
}
public static class Extensions {
  public static void ProcessContext<THasContext, TContext>(this THasContext t)
    where THasContext : IHasContext<TContext> 
    where TContext : class {
      //...
  }
}
public class SomeClassContext {/*...*/}
public class SomeClass : IHasContext<SomeClassContext> { 
  public SomeClassContext Context {get; set;}
  //...
}

//now in a function I can do:
  objSomeClass.ProcessContext<SomeClass, SomeClassContext>();

You see, because SomeClass already knows it contains <SomeClassContext> , so I want to do: 你看,因为SomeClass已经知道它包含<SomeClassContext> ,所以我想这样做:

  objSomeClass.ProcessContext(); 

without the <SomeClass, SomeClassContext> chunk. 没有<SomeClass, SomeClassContext>块。 Is it possible? 可能吗? How should I alter my code to achieve it? 我应该如何改变我的代码来实现它? Thank you :) 谢谢 :)

I don't see why you need two generic parameters. 我不明白为什么你需要两个通用参数。 Just use one: 只需使用一个:

public static class Extensions {
  public static void ProcessContext<TContext>(this IHasContext<TContext> t)
    where TContext : class {
    //...
  }
}

Then inference should work just fine: 然后推理应该工作得很好:

var obj = new SomeClass();
obj.ProcessContext();

There is one slight semantic difference between the two. 两者之间存在一个轻微的语义差异。 If the type SomeClass was a struct then your version would not box the argument t , while this version will causing boxing. 如果类型SomeClass是一个struct那么你的版本不会包装参数t ,而这个版本将导致装箱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM