0

请检查以下代码部分(简化版)

我关心的是ReadPath我需要调用我正在使用的类型的 GetPath() 的类。我怎样才能做到这一点?

public interface IPath
{
    string GetPath();
}

public class classA: IPath
{
    string GetPath()
    {
        return "C:\";
    }
}
public class classB: IPath
{
    string GetPath()
    {
        return "D:\";
    }
}
public class ReadPath<T> where T : IPath
{        
    public List<T> ReadType()
    {
        // How to call GetPath() associated with the context type.
    }        
}
4

4 回答 4

5
public interface IPath
{
    string GetPath();
}

public class classA : IPath
{
    public string GetPath()
    {
        return @"C:\";
    }
}
public class classB : IPath
{
    public string GetPath()
    {
        return @"D:\";
    }
}
public class ReadPath<T> where T : IPath, new()
{
    private IPath iPath;
    public List<T> ReadType()
    {
        iPath = new T();
        iPath.GetPath();
        //return some list of type T

    }
}
于 2012-05-22T07:18:09.923 回答
3

接口是基于实例的。因此,如果您想这样做,请传入一个实例并使用它。

但是,有一个基于类型的概念:属性:

[TypePath(@"C:\")]
public class classA
{
}
[TypePath(@"D:\")]
public class classB
{
}
public class ReadPath<T>
{        
    public static List<T> ReadType()
    {
        var attrib = (TypePathAttribute)Attribute.GetCustomAttribute(
              typeof(T), typeof(TypePathAttribute));
        var path = attrib.Path;
        ...
    }        
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct
    | AttributeTargets.Interface | AttributeTargets.Enum,
    AllowMultiple = false, Inherited = false)]
public class TypePathAttribute : Attribute
{
    public string Path { get; private set; }
    public TypePathAttribute(string path) { Path = path; }
}
于 2012-05-22T07:21:05.120 回答
2

另一个解决方案是实例成员,但您应该稍微更改泛型的声明:

public class ReadPath<T> where T : IPath, new() //default ctor presence
{       
    T mem = new T();
    public string  ReadType()
    {
        return mem.GetPath();
    }        
}

并不是说我改变了返回类型,因为不清楚你将如何适应返回string类型List<T>

于 2012-05-22T07:19:56.337 回答
0

您对 .net/c# 编程的几个不同方面感到困惑。
静态方法(你在这里甚至没有)不能通过接口定义,所以如果你对使用静态方法感兴趣,接口不会帮助你,你只能通过反射以通用的方式执行这样的方法。

您的代码有点不清楚,很难理解为什么您的 readtype 方法返回一个列表,以及您应该如何填写此列表。

于 2012-05-22T07:21:12.790 回答