使用泛型的C#接口静态方法调用 [英] C# interface static method call with generics

查看:169
本文介绍了使用泛型的C#接口静态方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来实现这一点,并且如果可能的话没有实例化对象:

 接口I 
{
static string GetClassName();
}

public class Helper
{

static void PrintClassName< T>()其中T:I
{
Console.WriteLine(T.GetClassName());
}
}


解决方案

一个扩展方法,而不是:

  public interface IMyInterface 
{
string GetClassName();
}

public static class IMyInterfaceExtensions
{
public static void PrintClassName< T>(this T input)
where T:IMyInterface
{
Console.WriteLine(input.GetClassName());






$ b这允许您添加静态扩展/实用程序方法,但你仍然需要一个IMyInterface实现的实例。



你不能有静态方法的接口,因为它没有意义,它们是没有实例,因此他们并没有真正的类型。

Is there a simple way to implement this, and if possible without instanciating an object :

interface I
{
     static  string GetClassName();
}

public class Helper
{

    static void PrintClassName<T>() where T : I
    {
         Console.WriteLine(T.GetClassName());
    }
}

解决方案

Try an extension method instead:

public interface IMyInterface
{
     string GetClassName();
}

public static class IMyInterfaceExtensions
{
    public static void PrintClassName<T>( this T input ) 
        where T : IMyInterface
    {
         Console.WriteLine(input.GetClassName());
    }
}

This allows you to add static extension/utility method, but you still need an instance of your IMyInterface implementation.

You can't have interfaces for static methods because it wouldn't make sense, they're utility methods without an instance and hence they don't really have a type.

这篇关于使用泛型的C#接口静态方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆