c# DateTime 添加不带扩展方法的属性

发布于 2024-09-29 20:39:37 字数 435 浏览 4 评论 0原文

我正在编写一个类库,我需要扩展 System.DateTime 以获得一个名为 VendorSpecificDay 的属性,这样

DateTime txnDate = DateTime.Today;

VendorSpecificDayEnum vendorDay = txnDate.VendorSpecificDay;

public enum VendorSpecificDayEnum
{
    Monday, Tuesday, ShoppingDay, HolidayDay
}

我意识到这是 System.Core 扩展方法的完美候选者,但该类库位于 .net 2.0 中(我知道我生活在黑暗时代)

鉴于扩展方法是语法糖,无论如何我可以在没有它们的情况下实现这一目标吗?

非常感谢

I am writing a class library where i need to extend System.DateTime to have a property called VendorSpecificDay such that

DateTime txnDate = DateTime.Today;

VendorSpecificDayEnum vendorDay = txnDate.VendorSpecificDay;

public enum VendorSpecificDayEnum
{
    Monday, Tuesday, ShoppingDay, HolidayDay
}

I realize that this is a perfect candidate for a System.Core Extension method, but the class library is in .net 2.0 ( i know i am living in dark ages )

Given that Extension methods are syntactical sugar, is there anyway i can achieve this without them ?

Many Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独享拥抱 2024-10-06 20:39:37

如果您可以访问 VS 2008 中的 C# 3.0 编译器,则即使您的项目面向 .NET 2.0,也可以使用扩展方法。只需定义您自己的 ExtensionAttribute

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}

只要该类型存在于引用的程序集中,您就可以使用 this 关键字来定义扩展方法,并可以像平常一样使用它们。

If you have access to the C# 3.0 compiler in VS 2008, you can use extension methods even if your project targets .NET 2.0. Just define your own ExtensionAttribute:

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}

As long as that type exists in a referenced assembly, you can use the this keyword to define extension methods, and can consume them like normal.

迷雾森÷林ヴ 2024-10-06 20:39:37

扩展方法只是静态方法,通过使用假的“this”指针来实现“实例方法”:

public static class Extensions
{
    public static int ANewFakeInstanceMethod(this SomeObject instance, string someParam)
    {
        return 0;
    }
}

您仍然可以像静态方法一样调用它 - 这就是编译器编译代码的方式,无论如何:

var inst = new SomeObject();
int result1 = inst.ANewFakeInstanceMethod("str");
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");

如果您不能获取扩展方法语法,即使您从静态方法定义中删除 this,您仍然可以使用第二种语法:

var inst = new SomeObject();
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");

public static class Extensions
{
    public static int ANewFakeInstanceMethod(SomeObject instance, string someParam)
    {
        return 0;
    }
}

BUT

您尝试实现的语法和用法没有意义。您正在获取一个现有的 DateTime 对象实例(它有自己的日期和时间值),并尝试在该实例上实现新的属性/方法 这将返回一些不相关的常量。

只需使用静态类,并在其上定义静态只读属性:

public static class KnownDates
{
    public static DateTime StSpruffingsDay
    {
        get
        {
            return new DateTime(1, 2, 3, 4);
        }
    }
}

如果这不是常量(例如,您当前年份需要它),则应该添加一个需要一年时间的方法 - 而不是尝试堵塞将其放入 DateTime 之上的扩展方法中,因为 DateTime 不仅仅包含一年。

public static class KnownDates
{
    public static DateTime GetTalkLikeAPirateDay(int year)
    {
        return new DateTime( // Todo: Calculate the value, based on Sept 19th
    }
}

如果您确实需要相对于 DateTime 获取它,那么将其传递给方法仍然会使您的代码更加清晰:

var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = KnownDates.GetTalkLikeAPirateDay(fiveMinutesAgo.Year);

...比直接从 DateTime< 调用它要好得多/代码> 实例:

var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = fiveMinutesAgo.GetTalkLikeAPirateDay();

Extension methods are just static methods, that implement "instance methods", by taking a fake "this" pointer:

public static class Extensions
{
    public static int ANewFakeInstanceMethod(this SomeObject instance, string someParam)
    {
        return 0;
    }
}

You can still invoke it just like a static method - this is how the compiler compiles your code, anyhow:

var inst = new SomeObject();
int result1 = inst.ANewFakeInstanceMethod("str");
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");

If you can't get the extension method syntax, you can still use the 2nd syntax, even if you strip the this from your static method definition:

var inst = new SomeObject();
int result2 = Extensions.ANewFakeInstanceMethod(inst, "str");

public static class Extensions
{
    public static int ANewFakeInstanceMethod(SomeObject instance, string someParam)
    {
        return 0;
    }
}

BUT

The syntax and usage you are trying to implement doesn't make sense. You're taking an existing DateTime object instance (which has its own values for date and time), and trying to implement a new property/method off that instance that will return some unrelated constant.

Just use a static class, and define static read-only properties on it:

public static class KnownDates
{
    public static DateTime StSpruffingsDay
    {
        get
        {
            return new DateTime(1, 2, 3, 4);
        }
    }
}

If this isn't a constant (as in, you need it for the current year), you should add a method that takes a year - not try to jam it into an extension method on top of a DateTime, because DateTime embodies more than just a year.

public static class KnownDates
{
    public static DateTime GetTalkLikeAPirateDay(int year)
    {
        return new DateTime( // Todo: Calculate the value, based on Sept 19th
    }
}

If you really need to get it relative to a DateTime, it still makes your code more clear to pass it to the method:

var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = KnownDates.GetTalkLikeAPirateDay(fiveMinutesAgo.Year);

... Than it does to invoke it straight off a DateTime instance:

var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
// ...
var arrrr = fiveMinutesAgo.GetTalkLikeAPirateDay();
始终不够爱げ你 2024-10-06 20:39:37

如果您在 Visual Studio 2008 中使用 .Net 2.0(使用 C# 3.0 编译器),则可以创建自己的 ExtensionAttribute,如下所示:

namespace System.Runtime.CompilerServices {
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class |
                    AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute { }
}

包含此属性后,您可以将能够在 .Net 2.0 项目中创建扩展方法。


如果您还在使用 VS2005,那您就不走运了。

If you're using .Net 2.0 in Visual Studio 2008 (with the C# 3.0 compiler), you can create your own ExtensionAttribute, like this:

namespace System.Runtime.CompilerServices {
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class |
                    AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute { }
}

After including this attribute, you'll be able to create extension methods in .Net 2.0 projects.


If you're still using VS2005, you're out of luck.

迷离° 2024-10-06 20:39:37

您的示例显示了一个(当前)不存在的扩展属性

“所有”扩展方法都为您提供更好的语法,您可以使用(稍微)丑陋的代码获得完全相同相同的东西:

static class DateTimeExtensions
{
   static IDictionary<DateTime, VendorSpecificDayEnum> m_VendorSpecificDays = new Dictionary<DateTime, VendorSpecificDayEnum>();
   public static VendorSpecificDayEnum GetVenderSpecificDay(/*this*/ DateTime dt)
   {
      return m_VendorSpecificDays[dt];
   }
}

然后您可以编写

VendorSpecificDayEnum vendorDay = DateTimeExtensions.GetVendorSpecificDay(txnDate);

Your sample shows an extension property which (currently) doesn't exist.

"All" extension methods get you is nicer syntax, you can get exactly the same thing with (slightly) uglier code:

static class DateTimeExtensions
{
   static IDictionary<DateTime, VendorSpecificDayEnum> m_VendorSpecificDays = new Dictionary<DateTime, VendorSpecificDayEnum>();
   public static VendorSpecificDayEnum GetVenderSpecificDay(/*this*/ DateTime dt)
   {
      return m_VendorSpecificDays[dt];
   }
}

You would then write

VendorSpecificDayEnum vendorDay = DateTimeExtensions.GetVendorSpecificDay(txnDate);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文