Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 传递要在另一个类中访问的类成员';s法_C#_Oop_Refactoring - Fatal编程技术网

C# 传递要在另一个类中访问的类成员';s法

C# 传递要在另一个类中访问的类成员';s法,c#,oop,refactoring,C#,Oop,Refactoring,我理解标题可能会让人困惑,所以让我来描述一下问题。我目前正在重构代码库的一部分 我们有很多类:比如a,B,C。这些类基本上是相似的,并且是一个简单的重构目标,除了我正在努力解决的这一行: // In Class A SomeType x = r?.abc?.FirstOrDefault(); // In Class B SomeType x = r?.def?.FirstOrDefault(); // In Class C SomeType x = r?.ghi?.FirstOrDefaul

我理解标题可能会让人困惑,所以让我来描述一下问题。我目前正在重构代码库的一部分

我们有很多类:比如
a
B
C
。这些类基本上是相似的,并且是一个简单的重构目标,除了我正在努力解决的这一行:

// In Class A
SomeType x = r?.abc?.FirstOrDefault();

// In Class B
SomeType x = r?.def?.FirstOrDefault();

// In Class C
SomeType x = r?.ghi?.FirstOrDefault();
r
是在此特定语句之前填充的对象。该类有一组成员:
abc
def
ghi
,等等。这些类中的每个
a
b
c
只访问其中一个。如何在我正在编写的新基类中重构这些语句

public class BaseClass {
    public T SomeMethod<T>(var param1, var param2, var member) {
        // Some processing. `r` gets populated
        SomeType x = r?.member?.FirstOrDefault(); // I want to do something like this but obviously this won't work. How to solve this?
    }
}
公共类基类{
公共T方法(变量参数1、变量参数2、变量成员){
//一些处理。`r`被填充
SomeType x=r?.member?.FirstOrDefault();//我想这样做,但显然不行。如何解决这个问题?
}
}

每个类访问哪个r成员是特定于类的行为,应该放在每个类中。

这看起来也更优雅。我也会试试这个。谢谢。这确实迫使我将
基类
设置为
抽象
。确实如此。我的印象是,这三门课基本相似,但并不完全相同。这意味着他们可以共享一个抽象基类。是的,这不是问题<代码>摘要对于设计而言,tbhPlus 1是有意义的。
public class BaseClass
{
    protected abstract SomeType GetX(OtherType r);

    … SomeType x = GetX(r);
}

public class A
{
    protected override SomeType GetX(OtherType r) => r?.abc?.FirstOrDefault();
}