为什么我不能将属性声明为System.IO.Path

时间:2013-06-07 04:59:02

标签: vb.net .net

我使用自定义类在方法之间传递数据。其中一个主要功能是图像处理,所以我有一个图像路径和一个自定义拇指路径作为我的类的属性。我想使用System.IO.Path类中包含的方法作为属性的一部分,但我似乎无法这样做。

我知道如何使用string类型代替System.IO.Path作为类型来实现此功能,因此我不需要任何人告诉我如何以这种方式执行此操作。我只是认为能够将ImagePath声明为System.IO.Path会更容易,因为我可以在Path属性上使用ImagePath方法。我必须错过一些关于声明类型的理解,我希望我能从这个问题中学习。

如何定义类:

Public Class myClass
    'structured information which will be passed to a replicator

    Public Property ID As Integer
    Public Property ImagePath As System.IO.Path '<== this doesn't work
    Public Property ThumbPath As System.IO.Path '<== this doesn't work
    Public Property GroupID As Byte
    Public Property SystemID As Byte
    Public Property Comment As String
    'Other properties
End Class

我想如何使用这个课程:

Public Function myReplicatorFunc(myObj as myClass)
    Dim myTempPath as string
    Dim myDBObj as myDBConnection

    'handle database connections

    myTempPath = myObj.ImagePath.GetDirectoryName() & "\" _
        myDBObj.GetIntID.toString() & "\" _
        myObj.ImagePath.GetExtension()

    My.Computer.FileSystem.RenameFile(myObj.ThumbPath.toString, myTempPath)

    'Other file movements for replication etc
End Function

为什么我不能将属性声明为System.IO.Path类?如果由于某种原因答案只是“否”(请解释原因)那么我如何使用System.IO.Path方法作为我的属性的扩展而无需重写为具有相同方法的精确副本的自定义类? / p>

2 个答案:

答案 0 :(得分:6)

您不能声明System.IO.Path的实例,因为它是一个静态类 - 它无法实例化。可以将其视为System.IO.Path命名空间下与路径相关的全局函数的分组。 (真正的命名空间只是System.IO,但因为Path是一个静态类,所以在功能上它的行为就好像只是一堆相关全局函数的命名空间。)

您的ImagePath属性需要为string,只需在需要该逻辑时将其传递给Path个函数。这有点不幸。

作为替代方案,您可以创建一个新类(抱歉,C#代码;我不是VB.NET专家):

using System;
using System.IO;
// import namespaces as necessary

public class Filename
{
    private string m_sFilename;

    public Filename ( string sFilename )
    {
        m_sFilename = sFilename;
    }

    public string FullName
    {
        get
        {
            return ( m_sFilename );
        }
        set
        {
            m_sFilename = value;
        }
    }

    public string FolderName
    {
        get
        {
            return ( Path.GetDirectoryName ( m_sFilename ) );
        }
    }

    // Add more properties / methods
    ...
}

有了这门课,你可以写:

private Filename m_oImagePath = null;

我在项目中的表现几乎相同,因为文件夹/文件路径的特定类型可以更容易地更新与路径名操作相关的逻辑。

答案 1 :(得分:1)

为什么不使用DirectoryInfo之类的:

Public Property ImagePath As System.IO.DirectoryInfo
Public Property ThumbPath As System.IO.DirectoryInfo