0

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

我知道如何通过使用string类型而不是类型来使其工作,System.IO.Path所以我不需要任何人告诉我如何做到这一点。我只是认为能够声明我ImagePath的 asSystem.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方法作为我的属性的扩展,而不用重写为具有相同方法的精确副本的自定义类?

4

2 回答 2

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;

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

于 2013-06-07T05:02:18.020 回答
1

为什么不使用DirectoryInfo像:

Public Property ImagePath As System.IO.DirectoryInfo
Public Property ThumbPath As System.IO.DirectoryInfo
于 2013-06-07T05:14:04.797 回答