【问题标题】:String Class: Create new Method, which returns a qlDate字符串类:创建新方法,该方法返回一个 qlDate
【发布时间】:2014-08-09 09:55:44
【问题描述】:

这里我有一个示例代码。我的目标是创建一个从String 返回ql.Date 的方法。是否可以?我从 Excel 设置日期字符串。但应用程序需要获得ql.Date()。现在我为任何 Date 写了一个返回方法。这很不雅。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MyClass myClass = new MyClass();
        myClass.Date1 = "08/04/2023";
        myClass.Date2 = "05/25/2012";
        // get would return a String, but I need the Date. 
        // So I call the method to get the Date:
        QuantLib.Date qlDate1 = myClass.returnQLDate1();
        QuantLib.Date qlDate2 = myClass.returnQLDate2();
        //My goal is a general method for all Dates (Date1, Date2, Date3,...) 
        // like this:
        QuantLib.Date qlDateX = myClass.DateX.toQLDate();
    }
}

我的班级:

public class MyClass
{
    string _Date1, _Date2; //string _Date3,...Date6,...double _rate, _cpn;
    public string Date1
    {
        private get { return _Date1; }
        set { _Date1 = value; }
    }

    public string Date2
    {
        private get { return _Date2; }
        set { _Date2 = value; }
    }

    public QuantLib.Date returnQLDate1()
    { return new QuantLib.Date(Date1, "mm/dd/yyyy"); }
    public QuantLib.Date returnQLDate2()
    { return new QuantLib.Date(Date2, "mm/dd/yyyy"); }
    //  public QuantLib.Date returnQLDate3()
    //  { return....       
}

【问题讨论】:

    标签: c# string date quantlib


    【解决方案1】:

    你可以创建extension method(当然名字是有争议的)

    public static QuantLib.Date ToQuantLibDate(this string value)
    {
        return new QuantLib.Date(value, "mm/dd/yyyy"); }
    }
    

    用法:

    var str = "08/04/2023";
    var date = str.ToQuantLibDate();
    

    【讨论】:

    • 非常感谢!但它只适用于新的“公共静态类 Ext”。他们有没有可能把它放在“公共课myClass”中
    • @user3924697 不,扩展方法只能在静态类中定义。只需创建一些类QuantLibExtensions
    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2012-07-04
    • 2013-03-31
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多