简体   繁体   中英

Is it possible to invoke class methods, set/get properties from console or powershell

If I write a class library in Visual Studio, is it possible to write a console application or powershell script which can call the methods or set/get the properties?

This is useful for testing APIs without having to create a form with loads of buttons etc.

I actually meant my executing my own class libraries. So if I write a class library with a namespace of ab with a class called c and a method in c, called test(), I'd want to execute this from a console app or PS.

Thanks

PowerShell makes it even easier than a console app, just open the PowerShell console and new up your object. You can then set properties, call methods, etc.

    $request = [Net.HttpWebRequest]::Create("http://somewhere/")
    $request.Method = "Get"
    $request.KeepAlive = $true
    $response = $request.GetResponse()
    $response.Close()

I should be clear this is really most useful for doing spot checking or trying out a new API. In most cases using some kind of unit testing framework (MSTest, NUnit, etc), as others have mentioned, will give you better return on your time investment.

It's easy to do from a Console Application -

Just add a reference to your class library, and use the types as needed. Just be aware you'll only be able to access your public API, since it's a separate assembly.

However, for testing purposes, you might want to consider using a testing framework. Visual Studio includes one (in Pro+ SKUs).

Yes Powershell is able to call methods and set properties of .Net classes directly.

$conn = new-object System.Data.SqlClient.SqlConnection($connstr)
$conn.Open()
$comm = new-object System.Data.SqlClient.SqlCommand()
$comm.Connection = $conn
$comm.CommandText = $sqlstr
$dr = $comm.ExecuteReader()
while($dr.Read())
{
   //...
}
$dr.Close()
$conn.Close()

As an alternative to Powershell, You can use IronPython:

import clr
clr.AddReference("MyLibrary");

foo = MyNamespace.MyClass()
foo.Property = "something"
print foo.GetSomeValue()

是的,您可以编写一个从库中调用方法的应用程序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM