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

もう 1 つの解決策はインスタンス メンバーですが、generic の宣言を少し変更する必要があります。

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

戻り値の型をどのように適合させるかが明確でないため、戻り値の型を変更したわけではありませstringList<T>

于 2012-05-22T07:19:56.337 に答える
0

.net/c# プログラミングのいくつかの異なる側面を混乱させています。
静的メソッド (ここにはありません) はインターフェイスを介して定義することはできないため、静的メソッドの使用に興味がある場合は、インターフェイスの wotn が役立ち、そのようなメソッドをリフレクションのみを使用して一般的な方法で実行できます。

あなたのコードは少し明確ではなく、 readtype メソッドがリストを返す理由と、このリストをどのように埋めるべきかを理解するのが難しいです。

于 2012-05-22T07:21:12.790 に答える