继承类中结构的功能 [英] Inherit functionality of a struct in a class

查看:70
本文介绍了继承类中结构的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构DateTime.我想创建一个名为myDateOfBirth的新类.我想在myDateOfBirth类中添加一些功能,例如isTodayBirthDay,WeakDayOfBirthDay等,但是DateTime的功能也应该可以从myDateOfBirth接受.
我有一些解决方案,但有缺陷.....
1.我们可以在myDateOfBirth和DateTime之间具有Has-A关系.但是以这种方式,我们无法通过myDateOfBirth或其对象直接访问DateTime的功能.

2.使用扩展方法.但是应用扩展方法只会将功能添加到DateTime,而我们不能导入myDateOfBirth.

I have a struct DateTime. I want to make a new class named myDateOfBirth. I want to add some functionality in myDateOfBirth class like isTodayBirthDay, WeakDayOfBirthDay etc., but functionalities of DateTime should also be accecible from myDateOfBirth.

some solutions I got but havings flaws.....
1. we can have Has-A relationship between myDateOfBirth and DateTime. But in that way we cann''t access functions of DateTime directly by myDateOfBirth or object of it.

2. Use extension mathods.But applying extension mathods will add functionality to DateTime only, and that we cann''t import in myDateOfBirth.

推荐答案

您错了关于扩展方法的可访问性,但除此之外,您应该编写一个提供所需功能的类.

You''re wrong about extension methods accessibility, but beyond that, you should write a class that provides the functionality you need.

public class Birthday
{
    public DateTime MyBirthday { get; set; }

    public Birthday(DateTime date)
    {
        this.MyBirthday = date;
    }
    
    public bool IsBirthday(DateTime date)
    {
        return (date.Day   == MyBirthday.Day && 
                date.Month == MyBirthday.Month);
    }

    public Weekday GetBirthdayWeekday()
    {
        return MyBirthday.DayOfWeek;
    }
}


这篇关于继承类中结构的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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