PowerTip of the Day-Creating Your Own Types

本文介绍如何在PowerShell环境中动态编译并使用C#代码创建.NET类型,演示了包含静态方法和实例方法的类的定义及调用过程。

原文地址: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里调用。

转载于:https://www.cnblogs.com/aspnetx/archive/2010/06/29/1767593.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值