2017-03-19 21 views
0

我试图使用API​​,我不能调用这个类的任何方法我怎样才能创建一个没有构造函数的类的对象,C#

namespace Ipfs.Api 
{ 

    /// <summary> 
    /// Manages the files/directories in IPFS. 
    /// </summary> 
    /// <remarks> 
    /// <para> 
    /// This API is accessed via the <see cref="IpfsClient.FileSystem"/> property. 
    /// </para> 
    /// </remarks> 
    /// <seealso href="https://github.com/ipfs/interface-ipfs-core/tree/master/API/files">Files API</seealso> 
    public class FileSystemApi 
    { 
     IpfsClient ipfs; 
     Lazy<DagNode> emptyFolder; 

     internal FileSystemApi(IpfsClient ipfs) 
     { 
      this.ipfs = ipfs; 
      this.emptyFolder = new Lazy<DagNode>(() => ipfs.Object.NewDirectoryAsync().Result); 
     } 

     /// <summary> 
     /// Add a file to the interplanetary file system. 
     /// </summary> 
     /// <param name="path"></param> 
     public Task<FileSystemNode> AddFileAsync(string path) 
     { 
      return AddAsync(
       new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), 
       Path.GetFileName(path)); 
     } 
} 

我想使用的API不修改它,我不能声明一个对象,因为我不能调用任何构造函数,并且我不能调用没有对象的任何方法,因为它们不是静态的。

Error while declaring the object

我应该怎么办?

+0

如果你打电话'VAR FSA会发生什么=新Ipfs.Api.FileSystemApi()' –

+0

如果没有你所定义的构造函数? ,那么总是有一个没有由编译器定义的参数的默认构造函数,所以你总是可以调用新的FileSystemApi()。阻止这个的唯一方法是定义一个类FileSystemApi中的私有或内部构造函数。在你的情况下,FIleSystemApi的设计者不希望文件外的任何人能够在这个类上调用new。所以没办法调用创建自己的类的实例 – Steve

+0

除非你使用反射http://stackoverflow.com/questions/2023193/c-sharp-instantiating-internal-class-with-private-constructor – Steve

回答

2

不能实例化类没有反射,这是一个有点哈克(取决于内部接口上,因为API维护者通常不关心保持内部位向后兼容是次优的。

的文档标签使你一条重要线索: “这个API是通过IpfsClient.FileSystem属性来访问。”

+0

你是对的,访问这些方法的正确方法是创建一个IpfsClient对象,然后通过其属性FileSystem调用这些方法。 –

+0

@GrantWinney首先解决了我的问题,但它是在评论中,我是否应该标记为正确或等待他创建答案?什么是正确的行为方式? –

+0

我在回答之前没有看到授予的评论,但他是第一个,我不觉得我增加了额外的东西。格兰特应该将他的评论转换为答案。 – RQDQ

相关问题