在哪里添加订阅 [英] Where to add subscription

查看:74
本文介绍了在哪里添加订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Account MyAccount = new Account(10000);
        subscriber Mysubscriber = new subscriber();

        public Form1()
        {
            InitializeComponent();
            MyAccount.TransactionMade += new TransactionHandler(Mysubscriber.SendNotification);
        }

       
        private void ButtonCredit(object sender, EventArgs e)
        {
            MyAccount.Credit(500);
            MessageBox.Show("your current balance is ", MyAccount.BalanceAmount.ToString());
        }
    }
}










namespace WindowsFormsApp1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }


    public delegate void TransactionHandler(object sender, TransactionEventArgs e); // Delegate Definition
    class Account
    {
        public event TransactionHandler TransactionMade; // Event Definition

        public int BalanceAmount;

        public Account(int amount)
        {
            this.BalanceAmount = amount;

        }

        public void Debit(int debitAmount)
        {
            if (debitAmount < BalanceAmount)
            {
                BalanceAmount = BalanceAmount - debitAmount;
                TransactionEventArgs e = new TransactionEventArgs(debitAmount, "Debited");
                OnTransactionMade(e); // Debit transaction made
            }
        }

        public void Credit(int creditAmount)
        {

            BalanceAmount = BalanceAmount + creditAmount;
            TransactionEventArgs e = new TransactionEventArgs(creditAmount, "Credited");
            OnTransactionMade(e); // Credit transaction made

        }

        protected virtual void OnTransactionMade(TransactionEventArgs e)
        {
            if (TransactionMade != null)
            {
                TransactionMade(this, e); // Raise the event 
            }
        }

    }


    public class TransactionEventArgs : EventArgs
    {
        public int TranactionAmount { get; set; }
        public string TranactionType { get; set; }

        public TransactionEventArgs(int amt, string type)
        {
            TranactionAmount = amt;
            TranactionType = type;
        }
    }


    public class subscriber
    {

        public void SendNotification(object sender, TransactionEventArgs e)
        {
            //Console.WriteLine("Your Account is {0} for Rs.{1} ", e.TranactionType, e.TranactionAmount);
            MessageBox.Show(e.TranactionType);
            MessageBox.Show(e.TranactionAmount.ToString());
        }



    }
}





我尝试了什么:



这是我发现的控制台示例。我试着把它变成一个winform。不确定我是否把这个位置放好了。

1.在那个位置创建MyAccount是不错的做法?在部分Class Form1中,或者我应该把它放在Class程序Main()中?



2.很高兴将事件订阅放在Form1()中?

3.如果需要,是否有必要提供取消订阅?



学习活动!谢谢!



What I have tried:

this is console example i found. i try to make it to a winform. not sure whether i put the position right.
1. is it good practice to create MyAccount in that position? inside partial Class Form1, or should i put it in Class program Main()?

2. good to put event subscription in Form1()?
3. is it necessary to put unsubscription , where if needed?

learning Event! thank you!

推荐答案

这是一个不寻常的问题。



首先关闭'Form1'并不好,总是给出有意义的名字:)



1. IMO这是一个很好的原则,有一个类,一个文件的原则,基本上放置每个类都是不同的文件,那个意味着没有它不是一个在Form类中定义另一个类的好地方,并且在Main.cs文件中输入同样糟糕,因为每个人都知道main包含一个名为'的静态类使用一个名为Main的静态方法编程。最终,您可能会将所有业务对象放在远离用户界面的单独dll中,在这种情况下,从一开始就可以将其组织起来。

如果您的意思是将成员放在表单中?即不是定义而是实例,那可能没问题。但是请考虑使用属性。通过这种方式,您可以获得访问器,只有在被分配之前获取并且在实际流程中永远不会发生时,才能添加默认值。没有理由使用在开发之外永远不会相关的值进行实例化。



2.是的。从类中进行通信应该使用一个事件,为什么你的表单应该为另一个类分配事件处理程序不太清楚,但原则上它很好,只记得在破坏表单时删除事件处理程序如果对象要在表单之后存在或者你可以通过参考保存很长时间的东西。



3.是否有必要取消订阅您订阅的活动? IMO永远!但最终在您的示例中,您的实例属于表单,因此事件订阅者将无法继续关闭您的表单。

表单是一个'一次性'对象,在.net中.Dispose方法是垃圾收集器线程调用的方法,如果你没有明确处理的话。每隔一段时间它就会遍历一次性对象的内存并在用户内存中查找引用,如果不存在,它将在对象上调用dispose。这使得它成为取消订阅的便利场所。
Quite an unusual question.

Well first off 'Form1' is not good, always give meaningfull names :)

1. IMO it is a good principle with "One class, one file" principle, essentially placing every class is different files and that means no it's not a good place to define another class inside a Form class and it is equally bad to put in in your Main.cs file, which in terms is a bit worse because 'everybody' knows the main contains one static class called 'Program' with one static method called Main. Ultimately you'll likely put all business objects in a seperate dll away from the user interface in which case it's practical to be organized for the future, from the start.
If you mean putting members in the form? i.e. not definitions but instances, then that could be fine. However consider using a property instead. This way you get accessors and you can add your default only if it is being 'get' before being assigned and in real flow that will never happen. no reason to instantiate with a value which will never be relevant outside of development.

2. Yes. communicating out from a class should be using an event, why Your form should assign the eventhandler for another class is less clear but in principle it's fine, just remember to remove eventhandlers when destroying the form if the objects are to exist after the form or you can keep stuff alive for a very long time by reference.

3. Is it necessary to unsubscribe to events you subscribe to ? IMO always! But ultimately in your example your instances belong to the form so the event subscribers will not survive closing your form.
A form is a 'disposable' object, in .net your .Dispose method is the one being called by the garbage collector thread if you didn't dispose explicitly. Every so often it's going to traverse the memory for disposable object and look for references in user memory, if none exist, it will call dispose on the object. This makes it a handy place to unsubscribe.


这篇关于在哪里添加订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆