2017-04-23 133 views
-3

在c#的String类中,它们隐藏了字符串类中所有方法的细节。例如,“ToLower”方法实现如下所示。C#隐藏方法实现代码

/// <summary> 
    /// Returns a copy of this string converted to lowercase. 
    /// </summary> 
    /// 
    /// <returns> 
    /// A string in lowercase. 
    /// </returns> 
    /// <filterpriority>1</filterpriority><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode"/></PermissionSet> 
    [__DynamicallyInvokable] 
    public string ToLower(); 

这就是所谓的封装。 现在我的问题是我怎么能这样做也为我自己的类?

预先感谢您。

+8

“这叫做封装”---它不是。 – zerkms

回答

6

您对情况的评估不正确。

我假设您在选择了String.ToLower()的情况下,在Visual Studio中按了F12(“转到定义”)。 而不是总是显示所选符号的源代码 - 如果源代码在您的系统上可用,它将只显示源代码 - 否则显示基于可用元数据的包含类型的大纲(即公共类型信息在.NET程序集文件中声明:非本地.NET .dll.exe文件)。

麻将:混杂的东西,如果你看一下使用展鹏反射器或其他CIL反汇编工具,那么你会看到这样一些其他String方法,没有任何来源拆解:

[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical] 
private extern String ReplaceInternal(Char oldChar, Char newChar); 

这一部分:MethodImplOptions.InternalCall意味着有没有CIL实现,而是在CLR内部实现(大概是在一些高性能的C++或x86汇编代码中)。但是,这不适用于实际上具有CIL实现的ToLower()(但它最终调用到TextInfo.InternalChangeCaseString也是InternalCall)。

关于自己的评论:

这就是所谓的封装。

不,这不是封装。 Encapsulation in OOP refers to how a class has been designed to hide implementation details到OOP消费者(例如System.Collections.Generic.List<T>如何不显示其内部T[]缓冲区)。这是无关的with obfuscating program source code

现在我的问题是,我怎么能这样做,也为我自己的班?

你不行。

当然,如果您不分发程序的源代码,然后在Visual Studio中的其他用户谁也按F12同样会看到相同的结果你:刚才类轮廓 - 但没有什么可以阻止有人使用Reflector等工具对其进行反汇编,并使用CIL混淆处理(使用Dotfuscator之类的工具)只能保护您的代码。

+0

这甚至不是混淆。它只是写一个头文件,只显示没有定义的声明。 (除了这不是C#中的东西。) –

+0

谢谢你,谢谢大家。我知道明白答案,我想我已经以令人困惑的方式提出了这个问题。 再次感谢您 –