簡體   English   中英

使用屬性生成自定義setter

[英]Generate custom setter using attributes

在我堅持使用對象數據庫的實例的類中,我不得不這樣做:

private string _name;
public string Name
    {
    get { return this._name; }
    set { _name = value; this.Save(); }
    }

而我寧願輸入這個:

[PersistedProperty(Name)]
private string _name;

其中PersistedProperty屬性生成一個Getter和Setter,就像默認的[Property()]屬性一樣,除了我想在生成的Setter中添加一行代碼。

有沒有辦法可以創建一個屬性來做到這一點? 希望,它適用於Intellisense。

默認的[Property()]屬性是如何做的呢? 如果我看到代碼,我可以嫁接......

注意:我實際上是在Boo中執行此操作,但我認為我會給c#代碼,因為更多人可能願意回答這個問題,但是,如果有一個Boo特定的解決方案,我全都耳朵!

更新:

我的目標只是減少打字和雜亂。 事實證明,最簡單的方法是使用一個腳本,該腳本根據我的類中的標記生成部分類。

從標記(與部分類一起)自動生成源代碼很容易,實際上看起來像是一種非常有前途的方法來解決我們通常嘗試使用繼承和泛型類型解決的一些問題。

這需要面向方面的編程 雖然在.NET中不直接支持,但可以通過第三方工具完成,例如PostSharp

但是,要使intellisense工作,必須在庫中完成,因為(最終)編譯的代碼將展開到完整屬性getter / setter中。

使用IMO屬性不容易實現。 也許您可以使用其他方法,例如擴展方法:

// Extension method that allows updating a property
// and calling .Save() in a single line of code.
public static class ISaveableExtensions
{
    public static void UpdateAndSave<T>(
        this ISaveable instance,
        Expression<Func<T>> propertyExpression, T newValue)
    {
        // Gets the property name
        string propertyName = ((MemberExpression)propertyExpression.Body).Member.Name;

        // Updates its value
        PropertyInfo prop = instance.GetType().GetProperty(propertyName);
        prop.SetValue(instance, newValue, null);

        // Now call Save
        instance.Save();
    }
}
...
// Some interface that implements the Save method
public interface ISaveable
{
    void Save();
}
...
// Test class
public class Foo : ISaveable
{
    public string Property { get; set; }

    public void Save()
    {
        // Some stuff here
        Console.WriteLine("Saving");
    }

    public override string ToString()
    {
        return this.Property;
    }
}
...
public class Program
{
    private static void Main(string[] args)
    {
        Foo d = new Foo();

        // Updates the property with a new value, and automatically call Save
        d.UpdateAndSave(() => d.Property, "newValue");

        Console.WriteLine(d);
        Console.ReadKey();
    }
}

它是類型安全的,自動完成友好的,但它需要更多的代碼而不僅僅是。 在所有setter中Save() ,所以不確定我會實際使用它...

暫無
暫無

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

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