【发布时间】:2020-02-27 19:33:24
【问题描述】:
我在 C# 中有一些类,我想在管道中使用它们,我看过有关它的文章,但我还没有做到。
这是我现在使用它的方式:
$suite = [MyProject.SuiteBuilder]::CreateSuite('my house')
$houseSet = $suite.AddSet('doors', 'These represents doors')
$houseSet.AddOption('blue', 'kitchen')
$houseSet.AddOption('black', 'bedreoom')
$houseSet.AddOption('white', 'toilet')
我希望能够像这样将它与管道一起使用:
$suite = [MyProject.SuiteBuilder]::CreateSuite('my house')
$suite | AddSet('doors', 'These represents doors') `
| AddOption('blue', 'kitchen') `
| AddOption('black', 'bedreoom') `
| AddOption('white', 'toilet')
这是我的 C# 类:
//SuiteBuilder.cs
public static class SuiteBuilder
{
public static Suite CreateTestSuite(string name)
{
return new Suite(name);
}
}
//Suite.cs
public class Suite : PSCmdlet
{
public string Name { get; set; }
public IEnumerable<Set> Sets { get; set; }
public Suite(string name)
{
Name = name;
Sets = new List<Set>();
}
// call this method in pipeline
public Set AddSet(string type, string description)
{
Sets.Add(new Set(type, description));
return Sets.Last();
}
}
//Set.cs
public class Set : PSCmdlet
{
public string Type { get; set; }
public string Description { get; set; }
public IEnumerable<Option> Options { get; set; }
public Set(string type, string description)
{
Type = type;
Description = description;
Options = new List<Option>();
}
// call this method from pipeline
public Set AddOption(string color, string place)
{
Options.Add(new Option(color, place));
return this;
}
}
//option.cs
public class Option : PSCmdlet
{
public string Color { get; set; }
public string Place { get; set; }
public Option(string color, string place)
{
Color = color;
Place = place;
}
}
我正在努力使这些函数可以在管道表单中调用。
我还在我需要调用的每条评论之前添加了一条评论,例如call this method in pipeline。
【问题讨论】:
-
为什么是管道? (对不起,我不能在 cmets 中添加换行符,请继续想象它们)
$houseSet = $suite.AddSet('doors', 'These represents doors').AddOption('blue', 'kitchen').AddOption('black', 'bedreoom').AddOption('white', 'toilet')不够吗?这是一个不复杂的折衷方案,应该可以在您的代码上运行,甚至无需对其进行更改。 -
@ensisNoctis 是的,只是管道看起来更清晰
-
它说here 你需要使用 System.Management.Automation.ParameterAttribute 来装饰参数,比如
[Parameter(ValueFromPipeline = true)]
标签: c# powershell cmdlet