“mThis”的起源是什么?

时间:2011-11-23 08:57:17

标签: android

我们的应用程序的Android部分有一些开发人员积极使用类成员变量的前缀“m *”。

“mThis”的起源基本上是什么:

class SomeClass {
    private final SomeClass mThis;
    SomeClass() {
        mthis = this;
    }
}

这个符号一般吗?

6 个答案:

答案 0 :(得分:5)

其实我猜这个问题更多的是关于m前缀,而不是将this作为你自己的字段的目标。

关于前缀,这是a coding convention used by android team:所有成员变量(又名字段)都以" m"为前缀。基本上就是这样。其他Android开发人员可能会使用它,因为他们浏览了android源代码,并认为在自己的代码中使用此约定是合适的。

顺便说一下,它在一般的java编程中并不常见,我相信常见的java编码标准通常不鼓励使用任何类型的前缀。

答案 1 :(得分:0)

我认为当你需要在内部类中传递对实例的引用并且你不想使用“完全限定的”这个时,它会派上用场。即SomeClass.this。然而,对我来说似乎是多余的。

答案 2 :(得分:0)

This article suggests it comes from ancient habits peculiar to the Microsoft ecosystem - 但是,struct的成员前面加上struct的一些简写,其中包含的是旧的 C习惯当标识符所有标识符(包括结构成员名称)在前八个字符中必须是唯一的。使用包含结构名称的简写版本对名称进行前缀是一种简单的机制,可确保使用唯一名称:

struct inode {
    int number;
    struct device *dev;
}

struct file_descriptor {
    int number;
    struct inode *i;
}

在这种情况下,number是重复的,非唯一的和麻烦。

较新版本的C通过将struct名称放入其名称空间而使这成为一个非问题,但这种习惯的某些部分已经延续:例如,Linux内核充满了:

struct iattr {
    unsigned int    ia_valid;
    umode_t     ia_mode;
    uid_t       ia_uid;
....

struct inode {
    /* RCU path lookup touches following: */
    umode_t         i_mode;
    uid_t           i_uid;
    gid_t           i_gid;
    const struct inode_operations   *i_op;
    struct super_block  *i_sb;
...

前导ia_i_来自struct iattrstruct inode - 这样可以更轻松地阅读此类链:

if (!IS_ERR(cookie) && path->dentry->d_inode->i_op->put_link)
    path->dentry->d_inode->i_op->put_link(path->dentry, nd, cookie);

(真的。fs/namei.c,我的来源中的第821和822行。)

答案 3 :(得分:0)

当你打算使用对象的成员(m是简称的)变量时,它避免意外地使用局部变量。

private String name;
private String mName;
public void setName(String name) {
    name = name; //wrong, just set the parameter variable to itself
    this.name = name; //ok, but has 'this.' which isn't a problem, but some people don't like it
    mName = name; //simples
}

答案 4 :(得分:0)

m表示成员变量,s表示静态。这是一个常见的命名约定。但是像中微子一样,我不太习惯。如果您使用现代IDE,语法颜色编码会为您提供相同的信息(实际上更多,因为无论原始编码器是否遵循命名约定,它都有效。)

答案 5 :(得分:-1)

我使用m前缀来定义类实例的全局变量。我不知道为什么,但是当我开始查看其他Android代码时,就像那样。