是否可以创建一个返回调用扩展方法的实例的扩展方法?
我想为继承的任何东西都有一个扩展方法ICollection<T>,返回该对象.就像jQuery总是返回jquery对象一样.
public static object AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
{
Run Code Online (Sandbox Code Playgroud)
我想象上面的内容,但我不知道如何回到父母的"this"对象类型来使用这样的东西:
List<int> myInts = new List<int>().AddItem(5);
Run Code Online (Sandbox Code Playgroud)
编辑:只是想明确我希望有一个通用约束解决方案.
在StringBuilder类中,我可以这样做:
StringBuilder sb = new StringBuilder();
sb.append( "asd").append(34);
Run Code Online (Sandbox Code Playgroud)
方法append返回StringBuilder实例,我可以连续调用它.
我的问题是可以在静态方法上下文中这样做吗?没有类实例
可能重复:
重载运算符 - >
嗨,
我已经看到operator->()它在被评估后被链接(重新应用),例如:
struct Bar
{
Bar() : m_str("Hello world!") {}
const string* operator->() const { return &m_str; }
string m_str;
};
struct Foo
{
const Bar& operator->() const { return m_bar; }
Bar m_bar;
};
int main()
{
Foo f;
cout << f->c_str() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
工作得很好,这需要三个operator->()进行评估- Foo::operator->(),Bar::operator->()和普通指针分辨率.
但它不适用于中间的Foo::operator->()指针- 如果返回指向Bar而不是引用的指针,它就不会编译.auto_ptr<auto_ptr<string>> 例如,同样如此.
它是否特定于非重载,operator->()因此它只应用一次而不会导致链接?可以在不使用的情况下使代码低于工作(*ptr2)-> ...吗?
int …Run Code Online (Sandbox Code Playgroud) 我必须实现一个Vector类,它设置一个多维向量的坐标,并在使用这个特定的代码调用时工作(我不能改变这部分):
const int NumOfDimensions = 5;
Vector x (NumOfDimensions);
x.Set(0, 1.1).Set(1, 1.2).Set(2, 1.3).Set(3, 1.4).Set(4, 1.5);
x.print();
Run Code Online (Sandbox Code Playgroud)
输出必须是这样的:
(1.1,1.2,1.3,1.4,1.5)
这是我尝试但无法让它工作:
class Vector {
float *coordinates;
int dimensions;
public:
Vector(int k)
{
coordinates = new float[k];
dimensions = k;
}
void Set(int k, float wsp)
{
//Vector x(k+1);
coordinates[k] = wsp;
//return x;
}
void print()
{
int i;
cout<<"(";
for(i=0; i<dimensions; i++)
cout<<coordinates[i]<<", ";
cout<<")"<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)
所以我知道函数Set需要改变并且可能返回一个对象,但我尝试了很多不同的方法而且它不起作用.我应该如何修改它?
我已经按层次结构组织了我的代码,并发现自己使用以下代码爬上树.
File clientFolder = task.getActionPlan().getClientFile().getClient().getDocumentsFolder();
Run Code Online (Sandbox Code Playgroud)
我没有钻进这个task物体; 我正在向它的父母钻研,所以我认为我在封装方面没有失去任何东西; 但是我脑子里的一面旗帜正在告诉我这样做有什么不好的事情.
这是错的吗?
阅读文章http://jeffkreeftmeijer.com/2011/method-chaining-and-lazy-evaluation-in-ruby/后,我开始寻找方法链和懒惰评估的更好解决方案.
我想我已经用以下五个规格封装了核心问题; 谁能让他们全部通过?
一切顺利:子类化,委托,元编程,但对后者不鼓励.
将依赖关系保持在最低限度是有利的:
require 'rspec'
class Foo
# Epic code here
end
describe Foo do
it 'should return an array corresponding to the reverse of the method chain' do
# Why the reverse? So that we're forced to evaluate something
Foo.bar.baz.should == ['baz', 'bar']
Foo.baz.bar.should == ['bar', 'baz']
end
it 'should be able to chain a new method after initial evaluation' do
foobar = Foo.bar
foobar.baz.should == ['baz', 'bar']
foobaz = Foo.baz
foobaz.bar.should == ['bar', 'baz'] …Run Code Online (Sandbox Code Playgroud) 我有一个方法可以通过方法链非常巧妙地编写:
return viewer.ServerReport.GetParameters()
.Single(p => p.Name == Convention.Ssrs.RegionParamName)
.ValidValues
.Select(v => v.Value);
Run Code Online (Sandbox Code Playgroud)
但是,我希望能够在每个点进行一些检查,因为如果任何链式方法返回意外结果,我希望提供有用的诊断信息.
为了达到这个目的,我需要打破所有链接并使用if块跟随每个调用.它使代码的可读性降低了很多.
理想情况下,我希望能够编织一些链式方法调用,这将允许我在每个点处理意外结果(例如抛出一个有意义的异常,例如,new ConventionException("The report contains no parameter")如果第一个方法返回一个空集合).谁能建议一个简单的方法来实现这样的事情?
编辑:
这是使用@ JeffreyZhao的答案的结果:
return viewer.ServerReport.GetParameters()
.Assert(result => result.Any(), "The report contains no parameter")
.SingleOrDefault(p => p.Name == Convention.Ssrs.RegionParamName)
.Assert(result => result != null, "The report does not contain a region parameter")
.ValidValues
.Select(v => v.Value)
.Assert(result => result.Any(), "The region parameter in the report does not contain any valid value");
Run Code Online (Sandbox Code Playgroud) 我想在这些问题中实现方法链接:
但是,我希望一旦使用了"属性",它就不能再使用了.例如,假设我有一个类"Myclass",我想允许使用定义"foo"和定义"bar"最多一次,我不关心最终的返回类型.从而:
val c = new Myclass
c foo //ok !
c foo bar // ok!
c foo foo // refuse to compile
c foo bar foo //refuse to compile
Run Code Online (Sandbox Code Playgroud)
我在这个问题上挣扎了一段时间,我的视力开始变得模糊!我尝试使用隐式类,但是,他们是否需要解析没有使用关联属性的对象,我无法找到他们是否需要通过从对象可用属性中删除它来"使用"该属性,以及再说一次,我怎么也找不到.
我目前正在使用反射API进行搜索,但对我来说它仍然有点模糊.
帮助将不胜感激!=)
我意识到这个一般性问题不适用于特殊类,但对于简单的类,当我们有多个构造函数,并且一个参数是另一个的干净子集时,用更长的时间调用构造函数会更好吗从列表较短的列表中列出,反之亦然?为什么?
public class A {
int x;
int y;
int z;
public A() {
this(0);
}
public A(int x) {
this (x, 0);
}
public A(int x, int y) {
this(x, y, 0);
}
public A(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
// some setup stuff needed for all A
}
}
Run Code Online (Sandbox Code Playgroud)
要么
public class A {
int x;
int y;
int z;
public A(int x, int y, int z) { …Run Code Online (Sandbox Code Playgroud) 我想知道在链接方法构建数据框时是否可以使用 pandas.drop方法删除行。
一旦数据帧存在,删除行就很简单:
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [5, 4, 3]})
print(df1)
# drop the entries that match "2"
df1 = df1[df1['A'] !=2]
print(df1)
Run Code Online (Sandbox Code Playgroud)
但是,我想在创建数据框时执行此操作:
df2 = (pd.DataFrame({'A': [1, 2, 3], 'B': [5, 4, 3]})
.rename(columns={'A': 'AA'})
# .drop(lambda x: x['A']!=2)
)
print(df2)
Run Code Online (Sandbox Code Playgroud)
注释行不起作用,但也许有正确的方法可以做到这一点。感谢您的任何投入。
method-chaining ×10
c# ×2
c++ ×2
java ×2
.net ×1
architecture ×1
chaining ×1
constructor ×1
dataframe ×1
linq ×1
pandas ×1
python ×1
ruby ×1
scala ×1