PowerTip of the Day-Creating Your Own Types

原文地址:http://app.en25.com/e/es.aspx?s=1403&e=5072&elq=a8251b41fe1a4d6297a0aecd8e466373

原文:

Did you know that you can compile any .NET source code on the fly and use this to create your own types? Here is an example illustrating how to create a new type from c# code that has both static and dynamic methods:

$source = @'
public class Calculator
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

public int Multiply(int a, int b)
    {
        return (a * b);
    }
}

'@
Add-Type -TypeDefinition $source
[Calculator]
[Calculator]
::Add(5,10)
$myCalculator = New-Object Calculator
$myCalculator.Multiply(3,12)

 

翻译:

你知道你可以编译任何即时.net源代码并且作为你的自定义类型使用它们吗?以下是一个示例阐述如何通过c#来创建一个拥有静态方法和实例方法的类型:

$source = @'
public class Calculator
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

public int Multiply(int a, int b)
    {
        return (a * b);
    }
}

'@
Add-Type -TypeDefinition $source
[Calculator]
[Calculator]
::Add(5,10)
$myCalculator = New-Object Calculator
$myCalculator.Multiply(3,12)

 

 

笔记:

直接在ps代码中创建一个类。

复习.net类的静态方法和实例方法的调用方法。

个人倾向于用先把逻辑编译成dll然后在ps里调用。

posted @ 2010-06-29 14:48  哥本哈士奇(aspnetx)  阅读(244)  评论(0编辑  收藏  举报