C# return a variable as read only from get; set;

后端 未结 7 2163
不思量自难忘°
不思量自难忘° 2021-02-02 07:30

I swear I have seen an example of this but have been googling for a bit and can not find it.

I have a class that has a reference to an object and need to have a GET; met

相关标签:
7条回答
  • 2021-02-02 08:14

    I have faced this problem in a certain way. I have a CategoryViewModel class, which have a property Category that I want private read-only :

    public CategoryViewModel
    {
        private Category { get; }
    
    }
    

    In fact, I want it to be exported as read-only to other class. However I can't do such thing. In my case (maybe it will help some other guys), I want to add it to a repository. The only way that I've found is to have a function with the repository as param 1, and an Action as param 2 :

    public void ApplyAction(ICategoryRepository repo, Action<ICategoryRepository, Category> action)
    {
        action(repo, Category);
    }
    

    Like that, from elsewhere, I can do such thing :

     categoryViewModel.ApplyAction(_repository, (r, c) => r.MarkForInsertOrUpdate(c));
    

    This can help other to expose there property only for certains cases and can manage them.

    0 讨论(0)
提交回复
热议问题