除了表达式之外,是否还有条件运算符之类的东西?

时间:2018-11-30 17:41:36

标签: c#

对于将值分配给可变变量,我可以使用以下内容:

className = special ? "Test" : "";

但是,如果我只想在special为true时才想调用一个函数,该怎么办?我尝试过

special?classNameIsTest() : classNameIsNotTest();

但这不起作用。有这样的东西吗?还是我应该继续使用

if(special) classNameIsTest();
else classNameIsNotTest();

3 个答案:

答案 0 :(得分:4)

如果两个方法都具有相同的签名(相同的参数和相同的返回类型),则可以执行此操作。例如,如果这两种方法都无效且不带参数

(special ? (Action)Foo : Bar).Invoke();

如果两种方法都采用整数但均无效

(special ? (Action<int>)Foo : Bar).Invoke(20);

如果两个方法都使用整数,字符串并返回布尔值

bool result = (special ? (Func<int, string, bool>)Foo : Bar).Invoke(20, "...");

因此您可以执行此操作,但我不这样做,因为这不是通常的编程方式。它只是添加样板代码。

答案 1 :(得分:3)

您可以使用此短语

var dummy = special ? Test1() : Test2();

但是两者不能为空,并且必须具有相同的返回类型。

所以...我通常不会使用它并坚持使用“ if”。您仅应使用此表达式使代码更易于维护和可读。

在您的情况下...我认为这会使代码难以理解。

答案 2 :(得分:2)

让我在开始这个答案之前先说我实际上不建议这样做,但是您可以使用扩展方法玩一些有趣的语法技巧。

public class Document
{
    public Document()
    {
        AllVersions = new HashSet < DocumentVersion >();
        History     = new HashSet < DocumentHistory >();
    }

    [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ]
    public int DocumentId { get; set; }
    public string Name { get; set; }
    public string Note { get; set; }
    public string Description { get; set; }
    public CheckoutStatus Status { get; set; } = CheckoutStatus.Locked;
    public ICollection < DocumentVersion > AllVersions { get; set; }
    public ICollection < DocumentHistory > History { get; set; }
}

public class DocumentVersion
{
    public DocumentVersion() => History     = new HashSet < DocumentVersionHistory >();

    public DocumentVersion ( byte [ ] content )
    {
        History = new HashSet < DocumentVersionHistory >();
        Content = content;
    }

    public int DocumentVersionId { get; set; }
    public int DocumentVersionNumber {get; set; }
    public string Note { get; set; }
    public PublishingStatus Status { get; set; }
    public byte [ ] Content { get; set; }
    public Document Document { get; set; }
    public ICollection < DocumentVersionHistory > History { get; set; }
}

protected override void OnModelCreating ( DbModelBuilder modelBuilder )
{
    modelBuilder.Entity < Document >().HasKey ( d => new { d.DocumentId } );
    modelBuilder.Entity < DocumentVersion >().HasKey ( dv => dv.DocumentVersionId ).HasIndex ( dv => new { dv.Document.DocumentId, dv.DocumentVersionNumber } );
    ...
}

然后像public static void Then(this bool x, Action whenTrue, Action whenFalse) { if (x) whenTrue(); else whenFalse(); }

一样使用它
相关问题