如何.NET框架低级API工作? [英] How does .NET framework low level APIs work?

查看:128
本文介绍了如何.NET框架低级API工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其中之一,我一直面临着是.NET框架类库实现的问题。

我知道的一些方法原来的执行情况:

例如:

 的MessageBox.show(...);
 

据我所知这个方法必须使用P / Invoke来调用Win32 API。

但这样的事情:

  System.Convert.ToInt32(myStr的);
 

其实我不知道它是如何工作的,因为int和字符串之间的转换是不可能在纯C#。(你可以做同样的事情,而不使用该方法?其实我也不知道)。

最后,如果你知道答案,请澄清这些概念对我来说speicially第二个例子。

解决方案
  

您可以做同样的事情,而无需使用这种方法?其实都能跟得上。

您绝对可以。下面是这样做的一个非常低效的方式 - 不考虑溢出,无效的输入或负数,但是它展示了总的原则

  INT ParseStringToInt32(文本字符串)
{
    INT结果为0;
    的foreach(文本字符C)
    {
        结果=结果* 10 +(C  - '0');
    }
    返回结果;
}
 

从根本上说,没有什么高深莫测的解析字符串为的Int32 的过程。它是在看每一个字符,考虑到它的数值,并做一些运算只是一个案件。

事实上,有些时候,这是值得做的手工 - 在Noda时间我们的我们自己的数字解析code 允许,而不必采取子被解析的字符数量有限。

One of the questions that i always faced was the implementation of .NET Framework class libraries.

I know some of the methods original implementation:

For example :

MessageBox.Show("...");

As i know this method must have used P/Invoke to call Win32 API.

but something like this:

System.Convert.ToInt32(mystr);

I actually don't know how it works because conversion between int and string is not possible in pure C#.(Can you do exact same thing without using that method? Actually I don't know).

Finally if you know the answer please clarify these concepts for me speicially the 2nd example.

解决方案

Can you do exact same thing without using that method? Actually Nope.

You absolutely can. Here's a really inefficient way of doing it - which doesn't consider overflow, invalid input or negative numbers, but demonstrates the general principle.

int ParseStringToInt32(string text)
{
    int result = 0;
    foreach (char c in text)
    {
        result = result * 10 + (c - '0');
    }
    return result;
}

Fundamentally there's nothing mystical about the process of parsing a string as an Int32. It's just a case of looking at each character, considering its numeric value, and doing some arithmetic.

Indeed, there are times when it's worth doing it manually - in Noda Time we have our own numeric parsing code to allow a limited number of characters to be parsed without having to take a substring.

这篇关于如何.NET框架低级API工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆