簡體   English   中英

在 C# 中到處聲明內聯變量(就像在聲明不可行的基礎構造函數調用中一樣)

[英]Declare inline variables everywhere in C# (like in a base-constructor-call where declaring is not feasible)

有些地方你不能像在基本構造函數調用中那樣聲明新變量( Exclaimer:這是一個展示問題的例子):

public class SportLicense : BaseEntity<SportLicense>
{
    public SportLicense() : base(
        tableName: new SportLicenseNames().EntityName,
        recordIdFieldName: new SportLicenseNames().RecordIdFieldName)
        { } 
}

內聯聲明SportLicenseNames的實例以避免創建多個實例會很好。 有時它只是關於優化性能,但我經常需要同一個實例第二次和第三次用於基本構造函數的另一個參數。

有幾個類似的場景,在表達式中聲明一個變量可以很好地避免創建方法體( Exclaimer:這是一個展示問題的例子):

public static TEntity ThrowIfNull<TEntity, TId>(this TEntity entity, TId recordId)
where TEntity : Entity, new()
{
    if (entity != null) return entity;
    var e = new TEntity();
    throw new($"Record not found in table '{e.EntityName}' with id '{recordId}'\r\nSELECT * FROM {e.EntityName} WHERE {e.GetPrimaryKeyColumn().Name} = '{recordId}'");
}

如果不是變量e我可以只使用表達式主體。 當然,我本可以創建另一個TEntity實例——每次我需要在字符串中使用它的值時——但這只是浪費。

我通過創建一個通用的擴展方法Var解決了這個問題,如下所示:

public static TObject Var<TObject>(this TObject obj, out TObject varName) => varName = obj;

這使我可以像這樣解決 base-constructor-call 的第一個問題:

public class SportLicense : BaseEntity<SportLicense>
{
    public SportLicense() : base(
        tableName: new SportLicenseNames().Var(out var sportLicenseNames).EntityName,
        recordIdFieldName: sportLicenseNames.RecordIdFieldName)
        { } 
}

第二種情況可以寫得更短,而不會影響實例數量的增加:

public static TEntity ThrowIfNull<TEntity, TId>(this TEntity entity, TId recordId)
    where TEntity : Entity, new()
    =>
        entity ??
        throw new(
            $"Record not found in table '{new TEntity().Var(out var e).EntityName.Var(out var eName)}' with id '{recordId}'\r\nSELECT * FROM {eName} WHERE {e.GetPrimaryKeyColumn().Name} = '{recordId}'");

通過這種方法,我通常可以優化性能(重用創建的屬性值等),而不必先編寫大量代碼來聲明變量等。

這個怎么樣:

public class SportLicense : BaseEntity<SportLicense>
{
    public SportLicense() : this(new SportLicenseNames()) { }

    private SportLicense(SportLicenseNames licenseNames) : base(
        tableName: licenseNames.EntityName,
        recordIdFieldName: licenseNames.RecordIdFieldName)
    { }
}

只創建一個SportLicenseNames實例,不需要擴展方法、 out變量等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM